import { Component, OnInit, Inject, ViewChild } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

import {
  DialogService,
  SnackBarService,
  AlertDialogComponent,
  AlertDialogResult,
  AlertDialogData
} from '@ucap-webmessenger/ui';

import {
  DetailResponse,
  DetailContent,
  MessageApiService,
  MessageType,
  DetailReceiver
} from '@ucap-webmessenger/api-message';

import {
  LoginResponse,
  RoleCode
} from '@ucap-webmessenger/protocol-authentication';
import { NGXLogger } from 'ngx-logger';
import {
  WriteComponent as UCapMessageWriteComponent,
  Message,
  MessageModify
} from '@ucap-webmessenger/ui-message';
import { UserInfo } from '@ucap-webmessenger/protocol-sync';
import {
  CreateChatDialogComponent,
  CreateChatDialogData,
  CreateChatDialogResult
} from '../chat/create-chat.dialog.component';
import {
  UserSelectDialogType,
  EnvironmentsInfo,
  KEY_VER_INFO
} from '@app/types';
import { take, tap } from 'rxjs/operators';
import { UserInfoSS } from '@ucap-webmessenger/protocol-query';
import { TranslateService } from '@ngx-translate/core';
import { VersionInfo2Response } from '@ucap-webmessenger/api-public';
import { SessionStorageService } from '@ucap-webmessenger/web-storage';
import { environment } from '../../../../../environments/environment';
import { EmployeeType } from '@ucap-webmessenger/protocol-room';
import { MessageStatusCode } from '@ucap-webmessenger/api';

export interface MessageWriteDialogData {
  loginRes: LoginResponse;
  environmentsInfo: EnvironmentsInfo;
  detail?: DetailResponse;
  detailContents?: string;
  receiverList?: (UserInfo | UserInfoSS)[];
}

// tslint:disable-next-line: no-empty-interface
export interface MessageWriteDialogResult {
  sendFlag: boolean;
  sendType?: MessageType;
}

export interface DownloadQueueForMessage extends DetailContent {
  downloadType: string;
}

@Component({
  selector: 'app-layout-messenger-message-write',
  templateUrl: './message-write.dialog.component.html',
  styleUrls: ['./message-write.dialog.component.scss']
})
export class MessageWriteDialogComponent implements OnInit {
  @ViewChild('messageWrite', { static: true })
  messageWrite: UCapMessageWriteComponent;

  curReceiverList: (UserInfo | UserInfoSS)[];

  sessionVerInfo: VersionInfo2Response;

  fileAllowSize: number;

  isModify = false;

  constructor(
    public dialogRef: MatDialogRef<
      MessageWriteDialogData,
      MessageWriteDialogResult
    >,
    @Inject(MAT_DIALOG_DATA) public data: MessageWriteDialogData,
    private messageApiService: MessageApiService,
    private snackBarService: SnackBarService,
    private translateService: TranslateService,
    private sessionStorageService: SessionStorageService,
    private logger: NGXLogger,
    private dialogService: DialogService
  ) {}

  ngOnInit(): void {
    this.sessionVerInfo = this.sessionStorageService.get<VersionInfo2Response>(
      KEY_VER_INFO
    );

    this.fileAllowSize =
      !!this.sessionVerInfo && this.sessionVerInfo.fileAllowSize
        ? this.sessionVerInfo.fileAllowSize
        : environment.productConfig.CommonSetting.defaultFileAllowSize;

    if (!!this.data.detail && !!this.data.detail.msgInfo) {
      this.isModify = true;
      this.curReceiverList = this.data.detail.recvList.map(recvInfo =>
        this.convertDetailReceivertoUserInfo(recvInfo)
      );
    } else {
      this.curReceiverList = this.data.receiverList;
    }
  }

  async onSelectReceiver(receiverList: UserInfo[]) {
    const result = await this.dialogService.open<
      CreateChatDialogComponent,
      CreateChatDialogData,
      CreateChatDialogResult
    >(CreateChatDialogComponent, {
      width: '600px',
      data: {
        type: UserSelectDialogType.EditChatMember,
        title: this.translateService.instant('message.selectRecipient'),
        curRoomUser: receiverList
      }
    });

    if (!!result && !!result.choice && result.choice) {
      // while (receiverList.length) {
      //   receiverList.pop();
      // }
      const selectedUserList: UserInfo[] = [];
      result.selectedUserList.forEach(v => {
        selectedUserList.push(v as UserInfo);
      });
      this.curReceiverList = selectedUserList;
    }
  }

  onSend(message: Message | MessageModify) {
    if (this.isModify) {
      this.onModifySend(message as MessageModify);
    } else {
      this.onNewSend(message as Message);
    }
  }
  onNewSend(message: Message) {
    this.messageApiService
      .sendMessage({
        ...message,
        userSeq: this.data.loginRes.userInfo.seq,
        userName: this.data.loginRes.userInfo.name,
        deviceType: this.data.environmentsInfo.deviceType,
        tokenKey: this.data.loginRes.tokenString,
        titleYn: '' !== message.title ? true : false
      })
      .pipe(take(1))
      .subscribe(
        res => {
          if (!!res && res.responseCode === MessageStatusCode.Success) {
            let msg = '';
            if (!!message.reservationTime) {
              msg = this.translateService.instant(
                'message.results.successForReservation'
              );
            } else {
              msg = this.translateService.instant(
                'message.results.successForSending'
              );
            }

            this.snackBarService.open(msg, '', {
              duration: 3000,
              verticalPosition: 'bottom'
            });

            this.dialogRef.close({ sendFlag: true, sendType: message.type });
          } else {
            let alertType = 'S';
            let errorMsg =
              this.translateService.instant('message.errors.failToSending') +
              `(${res.responseCode})`;
            switch (res.responseCode) {
              case MessageStatusCode.Fail_Msg_Reservation_Time_Null:
                errorMsg = this.translateService.instant(
                  'message.errors.failToReservationTimeEmpty'
                );
                alertType = 'A';
                break;
              case MessageStatusCode.Fail_Msg_Title_length:
                errorMsg = this.translateService.instant(
                  'message.errors.failToTitleLength'
                );
                alertType = 'A';
                break;
              case MessageStatusCode.Fail_Msg_Reservation_Time_Less:
              case MessageStatusCode.Fail_Msg_Edit_Reservation_Time_Less:
                errorMsg = this.translateService.instant(
                  'message.errors.failToReservationTimeLess'
                );
                alertType = 'A';
                break;
              case MessageStatusCode.Fail_Msg_Edit_Cancel_Reservation_Sended:
                errorMsg = this.translateService.instant(
                  'message.errors.failToReservationSended'
                );
                alertType = 'A';
                break;
              case MessageStatusCode.Fail_File_Size:
                errorMsg = this.translateService.instant(
                  'message.errors.failToFileSize'
                );
                alertType = 'A';
                break;
              case MessageStatusCode.Fail_File_Ext:
                errorMsg = this.translateService.instant(
                  'message.errors.failToFileExt'
                );
                alertType = 'A';
                break;
              case MessageStatusCode.Fail_Cancelled_Msg:
                errorMsg = this.translateService.instant(
                  'message.errors.failToCancelled'
                );
                alertType = 'A';
                break;
            }

            if (alertType === 'S') {
              this.snackBarService.open(errorMsg, '', {
                duration: 3000,
                verticalPosition: 'bottom'
              });
            } else {
              this.dialogService.open<
                AlertDialogComponent,
                AlertDialogData,
                AlertDialogResult
              >(AlertDialogComponent, {
                data: {
                  title: this.translateService.instant('message.errors.label'),
                  message: errorMsg
                }
              });
            }
          }
        },
        error => {
          this.snackBarService.open(
            this.translateService.instant('message.errors.failToSending'),
            '',
            {
              duration: 3000,
              verticalPosition: 'bottom'
            }
          );

          // this.dialogRef.close({});
        }
      );
  }
  onModifySend(message: MessageModify) {
    this.messageApiService
      .editReservationMessageEx({
        ...message,
        userSeq: this.data.loginRes.userInfo.seq,
        deviceType: this.data.environmentsInfo.deviceType,
        tokenKey: this.data.loginRes.tokenString,
        titleYn: '' !== message.title ? true : false
      })
      .pipe(take(1))
      .subscribe(
        res => {
          if (!!res && res.responseCode === MessageStatusCode.Success) {
            this.snackBarService.open(
              this.translateService.instant(
                'message.results.successForModifying'
              ),
              '',
              {
                duration: 3000,
                verticalPosition: 'bottom'
              }
            );

            this.dialogRef.close({ sendFlag: true, sendType: message.type });
          } else {
            let alertType = 'S';
            let errorMsg =
              this.translateService.instant('message.errors.failToSending') +
              `(${res.responseCode})`;
            switch (res.responseCode) {
              case MessageStatusCode.Fail_Msg_Reservation_Time_Null:
                errorMsg = this.translateService.instant(
                  'message.errors.failToReservationTimeEmpty'
                );
                alertType = 'A';
                break;
              case MessageStatusCode.Fail_Msg_Title_length:
                errorMsg = this.translateService.instant(
                  'message.errors.failToTitleLength'
                );
                alertType = 'A';
                break;
              case MessageStatusCode.Fail_Msg_Reservation_Time_Less:
              case MessageStatusCode.Fail_Msg_Edit_Reservation_Time_Less:
                errorMsg = this.translateService.instant(
                  'message.errors.failToReservationTimeLess'
                );
                alertType = 'A';
                break;
              case MessageStatusCode.Fail_Msg_Edit_Cancel_Reservation_Sended:
                errorMsg = this.translateService.instant(
                  'message.errors.failToReservationSended'
                );
                alertType = 'A';
                break;
              case MessageStatusCode.Fail_File_Size:
                errorMsg = this.translateService.instant(
                  'message.errors.failToFileSize'
                );
                alertType = 'A';
                break;
              case MessageStatusCode.Fail_File_Ext:
                errorMsg = this.translateService.instant(
                  'message.errors.failToFileExt'
                );
                alertType = 'A';
                break;
              case MessageStatusCode.Fail_Cancelled_Msg:
                errorMsg = this.translateService.instant(
                  'message.errors.failToCancelled'
                );
                alertType = 'A';
                break;
            }

            if (alertType === 'S') {
              this.snackBarService.open(errorMsg, '', {
                duration: 3000,
                verticalPosition: 'bottom'
              });
            } else {
              this.dialogService.open<
                AlertDialogComponent,
                AlertDialogData,
                AlertDialogResult
              >(AlertDialogComponent, {
                data: {
                  title: this.translateService.instant('message.errors.label'),
                  message: errorMsg
                }
              });
            }
          }
        },
        error => {
          this.snackBarService.open(
            this.translateService.instant('message.errors.failToModify'),
            '',
            {
              duration: 3000,
              verticalPosition: 'bottom'
            }
          );

          // this.dialogRef.close({});
        }
      );
  }

  onCancel() {
    this.dialogRef.close({ sendFlag: false });
  }

  getBtnValid() {
    return true;
  }

  private convertDetailReceivertoUserInfo(base: DetailReceiver): UserInfo {
    return {
      seq: base.userSeq,
      name: base.userName,
      profileImageFile: '',
      grade: '',
      intro: '',
      companyCode: '',
      hpNumber: '',
      lineNumber: '',
      email: '',
      isMobile: false,
      deptName: '',
      isFavorit: false,
      isBuddy: false,
      isActive: false,
      roleCd: RoleCode.Self,
      employeeNum: '',
      madn: '',
      hardSadn: '',
      fmcSadn: '',
      nameEn: '',
      nameCn: '',
      gradeEn: '',
      gradeCn: '',
      deptNameEn: '',
      deptNameCn: '',
      isPrivacyAgree: false,
      isValidLogin: false,
      employeeType: EmployeeType.Regular,
      nickName: '',

      order: ''
    };
  }
}
