import { Component, OnInit, Inject, ViewChild, OnDestroy } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { KEY_LOGIN_RES_INFO } from '@app/types/login-res-info.type';
import { KEY_VER_INFO } from '@app/types/ver-info.type';
import { SessionStorageService } from '@ucap-webmessenger/web-storage';

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, GroupDetailData } from '@ucap-webmessenger/protocol-sync';
import {
  UserInfoSS,
  UserInfoF,
  UserInfoDN
} from '@ucap-webmessenger/protocol-query';
import { DialogService, ConfirmDialogComponent, ConfirmDialogData, ConfirmDialogResult } from '@ucap-webmessenger/ui';
import { VersionInfo2Response } from '@ucap-webmessenger/api-public';
import { LoginResponse } from '@ucap-webmessenger/protocol-authentication';
import { map } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { SelectGroupDialogComponent, SelectGroupDialogData, SelectGroupDialogResult } from '../group/select-group.dialog.component';

export interface ProfileDialogData {
  userInfo: UserInfo | UserInfoSS | UserInfoF | UserInfoDN;
}

export interface ProfileDialogResult {}

@Component({
  selector: 'app-profile.dialog',
  templateUrl: './profile.dialog.component.html',
  styleUrls: ['./profile.dialog.component.scss']
})
export class ProfileDialogComponent implements OnInit, OnDestroy {
  loginRes: LoginResponse;
  sessionVerinfo: VersionInfo2Response;
  isMe: boolean;
  isBuddy: boolean;
  isFavorit: boolean;

  selectAllBuddy2Subscription: Subscription;

  constructor(
    public dialogRef: MatDialogRef<ProfileDialogData, ProfileDialogResult>,
    @Inject(MAT_DIALOG_DATA) public data: ProfileDialogData,
    private dialogService: DialogService,
    private sessionStorageService: SessionStorageService,
    private store: Store<any>
  ) {
    this.sessionVerinfo = this.sessionStorageService.get<VersionInfo2Response>(
      KEY_VER_INFO
    );
    this.loginRes = this.sessionStorageService.get<LoginResponse>(
      KEY_LOGIN_RES_INFO
    );
  }

  ngOnInit() {
    this.isMe = this.loginRes.userSeq === this.data.userInfo.seq;

    this.selectAllBuddy2Subscription = this.store
      .pipe(
        select(AppStore.MessengerSelector.SyncSelector.selectAllBuddy2),
        map(buddyList => {
          const users = buddyList.filter(
            buddy => buddy.seq === this.data.userInfo.seq
          );
          this.isBuddy = users.length > 0;
          if (this.isBuddy) {
            this.isFavorit = users[0].isFavorit;
          }
        })
      )
      .subscribe();
  }

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

  onClickChat(userInfo: UserInfo | UserInfoSS | UserInfoF | UserInfoDN) {
    if (userInfo.seq === this.loginRes.userSeq) {
      this.store.dispatch(
        ChatStore.openRoom({ userSeqList: [this.loginRes.talkWithMeBotSeq] })
      );
    } else {
      this.store.dispatch(ChatStore.openRoom({ userSeqList: [userInfo.seq] }));
    }

    this.dialogRef.close();
  }

  onClickToggleFavorit(param: {
    userInfo: UserInfo | UserInfoF;
    isFavorit: boolean;
  }) {
    this.store.dispatch(
      SyncStore.updateBuddy({
        seq: param.userInfo.seq,
        isFavorit: param.isFavorit
      })
    );
  }

  async onClickToggleBuddy(param: {
    userInfo: UserInfo | UserInfoF;
    isBuddy: boolean;
  }) {
    if (param.isBuddy) {
      // 동료추가.
      const result = await this.dialogService.open<
        SelectGroupDialogComponent,
        SelectGroupDialogData,
        SelectGroupDialogResult
      >(SelectGroupDialogComponent, {
        width: '600px',
        data: {
          title: 'Group Select'
        }
      });

      if (!!result && !!result.choice && result.choice) {
        if (!!result.group) {
          const oldGroup: GroupDetailData = result.group;
          const trgtUserSeq: number[] = [];
          result.group.userSeqs.map(seq => trgtUserSeq.push(seq));
          trgtUserSeq.push(param.userInfo.seq);

          this.store.dispatch(
            SyncStore.updateGroupMember({
              oldGroup,
              trgtUserSeq
            })
          );
        }
      }
    } else {
      // 동료삭제.
      const result = await this.dialogService.open<
        ConfirmDialogComponent,
        ConfirmDialogData,
        ConfirmDialogResult
      >(ConfirmDialogComponent, {
        width: '360px',
        data: {
          title: 'Delete Buddy',
          html: `[${param.userInfo.name} ${param.userInfo.grade}]를 그룹에서 삭제하시겠습니까?<br/>프로필에서 삭제하면 모든 그룹에서 삭제됩니다.`
        }
      });

      if (!!result && !!result.choice && result.choice) {
        this.store.dispatch(
          SyncStore.delBuddyAndClear({ seq: param.userInfo.seq })
        );
        this.isBuddy = false
      }
    }
  }
}
