import { exit } from './../../../../store/messenger/room/actions';
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import {
  ucapAnimations,
  DialogService,
  ConfirmDialogComponent,
  ConfirmDialogResult,
  ConfirmDialogData
} from '@ucap-webmessenger/ui';
import { NGXLogger } from 'ngx-logger';
import { Store, select } from '@ngrx/store';
import { Subscription, combineLatest, Observable } from 'rxjs';
import {
  RoomInfo,
  UserInfoShort,
  UserInfo as RoomUserInfo
} from '@ucap-webmessenger/protocol-room';
import * as AppStore from '@app/store';
import * as ChatStore from '@app/store/messenger/chat';
import * as RoomStore from '@app/store/messenger/room';
import { tap, debounceTime, delay } from 'rxjs/operators';
import {
  RoomUserDetailData,
  RoomUserData
} from '@ucap-webmessenger/protocol-sync';
import { VersionInfo2Response } from '@ucap-webmessenger/api-public';
import { SessionStorageService } from '@ucap-webmessenger/web-storage';
import { KEY_VER_INFO } from '@app/types/ver-info.type';
import { LoginResponse } from '@ucap-webmessenger/protocol-authentication';
import { MatMenuTrigger } from '@angular/material';
import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-layout-chat-left-sidenav-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.scss'],
  animations: ucapAnimations
})
export class ChatComponent implements OnInit, OnDestroy {
  @ViewChild('chatContextMenuTrigger', { static: true })
  chatContextMenuTrigger: MatMenuTrigger;
  chatContextMenuPosition = { x: '0px', y: '0px' };

  roomList: RoomInfo[];
  roomUserList: RoomUserDetailData[];
  roomUserShortList: RoomUserData[];
  sessionVerinfo: VersionInfo2Response;

  loginRes: LoginResponse;
  loginResSubscription: Subscription;
  roomSubscription: Subscription;

  isSearch = false;
  searchRoomList: RoomInfo[] = [];
  fgSearch: FormGroup;
  recommendedWordList: string[];
  filteredRecommendedWordList: string[];

  constructor(
    private store: Store<any>,
    private formBuilder: FormBuilder,
    private logger: NGXLogger,
    private dialogService: DialogService,
    private sessionStorageService: SessionStorageService
  ) {
    this.sessionVerinfo = this.sessionStorageService.get<VersionInfo2Response>(
      KEY_VER_INFO
    );
    this.recommendedWordList = [];
  }

  ngOnInit() {
    this.fgSearch = this.formBuilder.group({
      searchInput: null
    });

    this.fgSearch
      .get('searchInput')
      .valueChanges.pipe(debounceTime(100))
      .subscribe(value => {
        if (value !== null && value.length > 0) {
          this.filteredRecommendedWordList = this.recommendedWordList.filter(
            v => {
              return v.includes(value);
            }
          );
        } else {
          this.filteredRecommendedWordList = [];
        }
      });

    this.roomSubscription = combineLatest([
      this.store.pipe(
        select(AppStore.MessengerSelector.SyncSelector.selectAllRoom)
      ),
      this.store.pipe(
        select(AppStore.MessengerSelector.SyncSelector.selectAllRoomUser)
      ),
      this.store.pipe(
        select(AppStore.MessengerSelector.SyncSelector.selectAllRoomUserShort)
      )
    ])
      .pipe(
        tap(([room, roomUser, roomUserShort]) => {
          this.roomList = room;
          this.searchRoomList = room;
          this.roomUserList = roomUser;
          this.roomUserShortList = roomUserShort;

          const recommendedWordList = [];
          for (const r of room) {
            if (!!r.roomName && '' !== r.roomName.trim()) {
              recommendedWordList.push(r.roomName);
            }
          }
          for (const ru of roomUser) {
            for (const u of ru.userInfos) {
              if (u.seq !== this.loginRes.userSeq) {
                if (!!u.name && '' !== u.name.trim()) {
                  recommendedWordList.push(u.name);
                }
              }
            }
          }
          for (const ru of roomUserShort) {
            for (const u of ru.userInfos) {
              if (u.seq !== this.loginRes.userSeq) {
                if (!!u.name && '' !== u.name.trim()) {
                  recommendedWordList.push(u.name);
                }
              }
            }
          }

          this.recommendedWordList = [...recommendedWordList];
        })
      )
      .subscribe();

    this.loginResSubscription = this.store
      .pipe(
        select(AppStore.AccountSelector.AuthenticationSelector.loginRes),
        tap(loginRes => {
          this.loginRes = loginRes;
        })
      )
      .subscribe();
  }

  ngOnDestroy(): void {
    if (!!this.roomSubscription) {
      this.roomSubscription.unsubscribe();
    }
    if (!!this.loginResSubscription) {
      this.loginResSubscription.unsubscribe();
    }
  }

  onClickSearchCancel() {
    this.isSearch = false;
    this.searchRoomList = [];
    this.filteredRecommendedWordList = [];
  }

  onKeyDownEnter(event: KeyboardEvent, search: string) {
    event.preventDefault();
    event.stopPropagation();

    if (search.trim().length > 1) {
      this.isSearch = true;
      this.searchRoomList = this.roomList.filter(room => {
        if (room.roomName.indexOf(search) >= 0) {
          return true;
        } else if (
          this.getRoomUserList(room).filter(user =>
            user.seq !== this.loginRes.userSeq
              ? user.name.indexOf(search) >= 0
              : false
          ).length > 0
        ) {
          return true;
        } else {
          return false;
        }
      });
    } else {
      this.isSearch = false;
      this.searchRoomList = [];
    }
    setTimeout(() => (this.filteredRecommendedWordList = []), 200);
  }

  onContextMenuChat(event: MouseEvent, roomInfo: RoomInfo) {
    event.preventDefault();
    event.stopPropagation();

    this.chatContextMenuPosition.x = event.clientX + 'px';
    this.chatContextMenuPosition.y = event.clientY + 'px';
    this.chatContextMenuTrigger.menu.focusFirstItem('mouse');
    this.chatContextMenuTrigger.menuData = { roomInfo };
    this.chatContextMenuTrigger.openMenu();
  }

  async onClickContextMenu(type: string, roomInfo: RoomInfo) {
    switch (type) {
      case 'SELECT_ROOM':
        this.store.dispatch(
          ChatStore.selectedRoom({ roomSeq: roomInfo.roomSeq })
        );
        break;
      case 'TOGGLE_ALARM':
        this.store.dispatch(RoomStore.updateOnlyAlarm({ roomInfo }));
        break;
      case 'EXIT_ROOM':
        {
          const result = await this.dialogService.open<
            ConfirmDialogComponent,
            ConfirmDialogData,
            ConfirmDialogResult
          >(ConfirmDialogComponent, {
            data: {
              title: 'Exit Room',
              html: `대화방을 나가시겠습니까?<br/>나가기를 하면 대화내용 및 대화방 정보가 삭제됩니다.`
            }
          });

          if (!!result && !!result.choice && result.choice) {
            this.store.dispatch(RoomStore.exit({ roomSeq: roomInfo.roomSeq }));
          }
        }
        break;
    }
  }

  getRoomUserList(roomInfo: RoomInfo): (RoomUserInfo | UserInfoShort)[] {
    if (!!this.roomUserList && 0 < this.roomUserList.length) {
      const i = this.roomUserList.findIndex(
        value => roomInfo.roomSeq === value.roomSeq
      );
      if (-1 < i) {
        return this.roomUserList[i].userInfos;
      }
    }

    if (!!this.roomUserShortList && 0 < this.roomUserShortList.length) {
      const i = this.roomUserShortList.findIndex(
        value => roomInfo.roomSeq === value.roomSeq
      );
      if (-1 < i) {
        return this.roomUserShortList[i].userInfos;
      }
    }
  }
}
