import { exit } from './../../../../store/messenger/room/actions';
import {
  Component,
  OnInit,
  OnDestroy,
  ViewChild,
  AfterViewChecked,
  Input,
  ChangeDetectorRef
} 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 } from 'rxjs/operators';
import { 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';
import { LoginResponse } from '@ucap-webmessenger/protocol-authentication';
import { MatMenuTrigger } from '@angular/material';
import { FormGroup, FormBuilder } from '@angular/forms';
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import { PerfectScrollbarDirective } from 'ngx-perfect-scrollbar';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-layout-chat-left-sidenav-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.scss'],
  animations: ucapAnimations
})
export class ChatComponent implements OnInit, OnDestroy, AfterViewChecked {
  @Input()
  isVisible = true;

  @ViewChild('cvsvChatList', { static: false })
  cvsvChatList: CdkVirtualScrollViewport;

  @ViewChild(PerfectScrollbarDirective, { static: false })
  psDirectiveRef?: PerfectScrollbarDirective;

  @ViewChild('chatContextMenuTrigger', { static: true })
  chatContextMenuTrigger: MatMenuTrigger;
  chatContextMenuPosition = { x: '0px', y: '0px' };

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

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

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

  /** 채팅 리스트에 virture scroll의 size check */
  isInitList = false;

  constructor(
    private store: Store<any>,
    private formBuilder: FormBuilder,
    private logger: NGXLogger,
    private dialogService: DialogService,
    private sessionStorageService: SessionStorageService,
    private translateService: TranslateService,
    private changeDetectorRef: ChangeDetectorRef
  ) {
    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.selectAllRoomUserShort)
      )
    ])
      .pipe(
        tap(([room, roomUserShort]) => {
          if (!room || !roomUserShort || roomUserShort.length === 0) {
            return;
          }

          this.roomList = room;
          this.roomUserShortList = roomUserShort;

          const recommendedWordList = [];
          for (const r of room) {
            if (!!r.roomName && '' !== r.roomName.trim()) {
              recommendedWordList.push(r.roomName);
            }
          }
          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.filter(
              (item, index) => recommendedWordList.indexOf(item) === index
            )
          ];

          if (!!this.isSearch) {
            this.searchRoomList = room.filter(
              roomInfo =>
                this.searchRoomList.filter(
                  sInfo => sInfo.roomSeq === roomInfo.roomSeq
                ).length > 0
            );
          }

          if (!!this.psDirectiveRef) {
            this.psDirectiveRef.update();
          }

          // this.changeDetectorRef.detectChanges();
        })
      )
      .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();
    }
  }

  ngAfterViewChecked(): void {
    if (
      !!this.cvsvChatList &&
      !!this.roomList &&
      this.roomList.length > 0 &&
      !this.isInitList &&
      this.isVisible
    ) {
      this.isInitList = true;
      this.cvsvChatList.checkViewportSize();
    }
  }

  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: this.translateService.instant('chat.exitFromRoom'),
              html: this.translateService.instant('chat.confirmExitFromRoom')
            }
          });

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

  getRoomUserList(roomInfo: RoomInfo): (RoomUserInfo | UserInfoShort)[] {
    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;
      }
    }
  }
}
