import {
  Component,
  OnInit,
  OnDestroy,
  Inject,
  EventEmitter,
} from '@angular/core';

import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { NGXLogger } from 'ngx-logger';
import { FileEventJson } from '@ucap-webmessenger/protocol-event';
import { DeviceType, FileUtil, MimeUtil } from '@ucap-webmessenger/core';
import { NativeService, UCAP_NATIVE_SERVICE } from '@ucap-webmessenger/native';
import { take, map, finalize, tap } from 'rxjs/operators';
import { SnackBarService } from '@ucap-webmessenger/ui';
import {
  FileDownloadItem,
  CommonApiService,
} from '@ucap-webmessenger/api-common';

export interface FileViewerDialogData {
  fileInfo: FileEventJson;
  downloadUrl: string;
  userSeq: number;
  deviceType: DeviceType;
  token: string;
}

export interface FileViewerDialogResult {}

@Component({
  selector: 'app-layout-common-file-viewer',
  templateUrl: './file-viewer.dialog.component.html',
  styleUrls: ['./file-viewer.dialog.component.scss'],
})
export class FileViewerDialogComponent implements OnInit, OnDestroy {
  fileInfo: FileEventJson;
  downloadUrl: string;
  userSeq: number;
  deviceType: DeviceType;
  token: string;

  fileDownloadUrl: string;

  constructor(
    public dialogRef: MatDialogRef<
      FileViewerDialogData,
      FileViewerDialogResult
    >,
    @Inject(MAT_DIALOG_DATA) public data: FileViewerDialogData,
    @Inject(UCAP_NATIVE_SERVICE) private nativeService: NativeService,
    private snackBarService: SnackBarService,
    private commonApiService: CommonApiService,
    private logger: NGXLogger
  ) {
    this.fileInfo = data.fileInfo;
    this.downloadUrl = data.downloadUrl;
    this.userSeq = data.userSeq;
    this.deviceType = data.deviceType;
    this.token = data.token;

    this.fileDownloadUrl = this.commonApiService.urlForFileTalkDownload(
      {
        userSeq: this.userSeq,
        deviceType: this.deviceType,
        token: this.token,
        attachmentsSeq: this.fileInfo.attachmentSeq,
      },
      this.downloadUrl
    );
  }

  ngOnInit() {}

  ngOnDestroy(): void {}

  onDownload(fileDownloadItem: FileDownloadItem): void {
    this.commonApiService
      .fileTalkDownload(
        {
          userSeq: this.userSeq,
          deviceType: this.deviceType,
          token: this.token,
          attachmentsSeq: this.fileInfo.attachmentSeq,
          fileDownloadItem,
        },
        this.downloadUrl
      )
      .pipe(
        take(1),
        map(async rawBlob => {
          const mimeType = MimeUtil.getMimeFromExtension(this.fileInfo.fileExt);
          const blob = rawBlob.slice(0, rawBlob.size, mimeType);

          FileUtil.fromBlobToBuffer(blob)
            .then(buffer => {
              this.nativeService
                .saveFile(buffer, this.fileInfo.fileName, mimeType)
                .then(result => {
                  if (!!result) {
                    this.snackBarService.open(
                      `파일이 경로[${result}]에 저장되었습니다.`,
                      '',
                      {
                        duration: 3000,
                        verticalPosition: 'bottom',
                      }
                    );
                  } else {
                    this.snackBarService.open('파일 저장에 실패하였습니다.');
                  }
                })
                .catch(reason => {
                  this.snackBarService.open('파일 저장에 실패하였습니다.');
                });
            })
            .catch(reason => {
              this.logger.error('download', reason);
            });
        }),
        finalize(() => {
          setTimeout(() => {
            fileDownloadItem.downloadingProgress$ = undefined;
          }, 1000);
        })
      )
      .subscribe();
  }

  onClosedViewer(): void {
    this.dialogRef.close();
  }
}
