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

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

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

import { LoginResponse } 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 } 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';

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;

  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;
    }
  }

  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();
      }
      result.selectedUserList.forEach(v => {
        receiverList.push(v as UserInfo);
      });
    }
  }

  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 => {
          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 });
        },
        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 => {
          this.snackBarService.open(
            this.translateService.instant(
              'message.results.successForModifying'
            ),
            '',
            {
              duration: 3000,
              verticalPosition: 'bottom'
            }
          );

          this.dialogRef.close({ sendFlag: true, sendType: message.type });
        },
        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;
  }
}
