import { UserSelectDialogType } from './../../../types/userselect.dialog.type';
import {
  Component,
  OnInit,
  Output,
  EventEmitter,
  ViewChildren,
  QueryList,
  ElementRef,
  OnDestroy
} from '@angular/core';
import { NGXLogger } from 'ngx-logger';
import { ucapAnimations, DialogService } from '@ucap-webmessenger/ui';
import {
  CreateChatDialogComponent,
  CreateChatDialogData,
  CreateChatDialogResult
} from '@app/layouts/messenger/dialogs/chat/create-chat.dialog.component';
import { Observable, Subscription } from 'rxjs';
import { Store, select } from '@ngrx/store';

import * as AppStore from '@app/store';
import * as ChatStore from '@app/store/messenger/chat';
import * as SyncStore from '@app/store/messenger/sync';
import { UserInfo } from '@ucap-webmessenger/protocol-sync';
import {
  UserInfoSS,
  UserInfoF,
  UserInfoDN
} from '@ucap-webmessenger/protocol-query';
import { MatTabChangeEvent, MatTabGroup } from '@angular/material';
import { RightDrawer } from '@app/types';
import { LoginResponse } from '@ucap-webmessenger/protocol-authentication';
import { SessionStorageService } from '@ucap-webmessenger/web-storage';
import { KEY_LOGIN_RES_INFO } from '@app/types/login-res-info.type';
import { VersionInfo2Response } from '@ucap-webmessenger/api-public';
import { KEY_VER_INFO } from '@app/types/ver-info.type';

export enum MainMenu {
  Group = 'GROUP',
  Chat = 'CAHT',
  Organization = 'ORGANIZATION',
  Message = 'MESSAGE',
  Call = 'CALL',
  Conversation = 'CONVERSATION'
}

@Component({
  selector: 'app-layout-messenger-left-side',
  templateUrl: './left-side.component.html',
  styleUrls: ['./left-side.component.scss'],
  animations: ucapAnimations
})
export class LeftSideComponent implements OnInit, OnDestroy {
  @Output()
  openProfile = new EventEmitter<
    UserInfo | UserInfoSS | UserInfoF | UserInfoDN
  >();

  @ViewChildren('tabs') tabs: QueryList<ElementRef<HTMLDivElement>>;
  currentTabLable: string;

  badgeChatUnReadCount: number;
  badgeChatUnReadCountSubscription: Subscription;

  /** 조직도에서 부서원 선택 */
  selectedUserList: (UserInfo | UserInfoSS | UserInfoF | UserInfoDN)[] = [];

  /** FAB */
  fabButtonShow = true;
  fabButtons: { icon: string; tooltip?: string; divisionType?: string }[];

  MainMenu = MainMenu;

  sessionVerinfo: VersionInfo2Response;
  loginRes: LoginResponse;

  constructor(
    private store: Store<any>,
    private dialogService: DialogService,
    private sessionStorageService: SessionStorageService,
    private logger: NGXLogger
  ) {
    this.loginRes = this.sessionStorageService.get<LoginResponse>(
      KEY_LOGIN_RES_INFO
    );
    this.sessionVerinfo = this.sessionStorageService.get<VersionInfo2Response>(
      KEY_VER_INFO
    );
  }

  ngOnInit() {
    this.badgeChatUnReadCountSubscription = this.store
      .pipe(
        select(AppStore.MessengerSelector.SyncSelector.selectChatUnreadCount)
      )
      .subscribe(count => {
        this.badgeChatUnReadCount = count;
      });

    this.setFabInitial(MainMenu.Group);
    this.currentTabLable = MainMenu.Group;
  }

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

    this.logger.debug('-----------------------LeftSideComponent ngOnDestroy');
  }

  async onClickNewChat(type: string = 'NORMAL') {
    const result = await this.dialogService.open<
      CreateChatDialogComponent,
      CreateChatDialogData,
      CreateChatDialogResult
    >(CreateChatDialogComponent, {
      width: '600px',
      data: {
        type: UserSelectDialogType.NewChat,
        title: type === 'TIMER' ? 'New Timer Chat' : 'New Chat'
      }
    });

    if (!!result && !!result.choice && result.choice) {
      if (!!result.selectedUserList && result.selectedUserList.length > 0) {
        const userSeqs: number[] = [];
        result.selectedUserList.map(user => userSeqs.push(user.seq));

        if (type === 'NORMAL') {
          this.store.dispatch(ChatStore.openRoom({ userSeqList: userSeqs }));
        } else if (type === 'TIMER') {
          this.store.dispatch(
            ChatStore.openRoom({ userSeqList: userSeqs, isTimeRoom: true })
          );
        }
      }
    }
  }

  async onClickNewGroupAndMember() {
    const result = await this.dialogService.open<
      CreateChatDialogComponent,
      CreateChatDialogData,
      CreateChatDialogResult
    >(CreateChatDialogComponent, {
      width: '600px',
      data: {
        type: UserSelectDialogType.NewGroup,
        title: 'New Group'
      }
    });

    if (!!result && !!result.choice && result.choice) {
      if (
        !!result.selectedUserList &&
        // result.selectedUserList.length > 0 &&
        result.groupName.trim().length > 0
      ) {
        const userSeqs: number[] = [];
        result.selectedUserList.map(user => userSeqs.push(user.seq));

        this.store.dispatch(
          SyncStore.createGroupAndBuddy({
            groupName: result.groupName,
            trgtUserSeq: userSeqs
          })
        );
      }
    }
  }

  onClickOpenProfile(userInfo: UserInfo | UserInfoSS | UserInfoF | UserInfoDN) {
    this.openProfile.emit(userInfo);
  }

  onSelectedTabChange(event: MatTabChangeEvent) {
    this.setFabInitial(event.tab.ariaLabel);
    this.currentTabLable = event.tab.ariaLabel;

    this.tabs.forEach(tab => {
      if (`tabs-${event.index}` === tab.nativeElement.id) {
        tab.nativeElement.style.display = 'block';
      } else {
        tab.nativeElement.style.display = 'none';
      }
    });
  }
  setFabInitial(type: string) {
    switch (type) {
      case MainMenu.Group:
        {
          this.fabButtonShow = true;
          this.fabButtons = [
            {
              icon: 'add',
              tooltip: 'New Group Add',
              divisionType: 'GROUP_NEW_ADD'
            }
          ];
        }
        break;
      case MainMenu.Chat:
        {
          this.fabButtonShow = true;
          this.fabButtons = [
            {
              icon: 'timer',
              tooltip: 'New Timer Chat',
              divisionType: 'CHAT_NEW_TIMER_ADD'
            },
            {
              icon: 'chat',
              tooltip: 'New Chat',
              divisionType: 'CAHT_NEW_ADD'
            }
          ];
        }
        break;
      //  case MainMenu.Organization:
      //   {

      //   }
      //   break;
      //  case MainMenu.Call:
      //   {

      //   }
      //   break;

      default: {
        this.fabButtonShow = false;
      }
    }
  }

  onCheckAllUser(params: {
    isChecked: boolean;
    userInfos: (UserInfo | UserInfoSS | UserInfoF | UserInfoDN)[];
  }) {
    params.userInfos.forEach(userInfo => {
      if (params.isChecked) {
        if (
          this.selectedUserList.filter(user => user.seq === userInfo.seq)
            .length === 0
        ) {
          this.selectedUserList = [...this.selectedUserList, userInfo];
        }
      } else {
        this.selectedUserList = this.selectedUserList.filter(
          user => user.seq !== userInfo.seq
        );
      }
    });
  }

  /** 조직도>부서원 :: 리스트의 checkbox 의 이벤트를 받아 선택된 유저리스트를 수집. */
  onCheckUser(params: {
    isChecked: boolean;
    userInfo: UserInfo | UserInfoSS | UserInfoF | UserInfoDN;
  }) {
    if (params.isChecked) {
      if (
        params.userInfo &&
        this.selectedUserList.filter(user => user.seq === params.userInfo.seq)
          .length === 0
      ) {
        this.selectedUserList = [...this.selectedUserList, params.userInfo];
      }
    } else {
      this.selectedUserList = this.selectedUserList.filter(
        user => user.seq !== params.userInfo.seq
      );
    }
  }
  onToggleUser(userInfo: UserInfo | UserInfoSS | UserInfoF | UserInfoDN) {
    if (
      this.selectedUserList.filter(user => user.seq === userInfo.seq).length ===
      0
    ) {
      this.selectedUserList = [...this.selectedUserList, userInfo];
    } else {
      this.selectedUserList = this.selectedUserList.filter(
        item => item.seq !== userInfo.seq
      );
    }
  }

  /** FAB */
  onClickFab(params: { btn: any }) {
    const btn = params.btn as {
      icon: string;
      tooltip?: string;
      divisionType?: string;
    };

    switch (btn.divisionType) {
      case 'GROUP_NEW_ADD':
        {
          this.onClickNewGroupAndMember();
        }
        break;

      case 'CAHT_NEW_ADD':
        {
          this.onClickNewChat('NORMAL');
        }
        break;
      case 'CHAT_NEW_TIMER_ADD':
        {
          this.onClickNewChat('TIMER');
        }
        break;
    }
  }
}
