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;

  fileDownloadItem: FileDownloadItem;

  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(): void {
    this.fileDownloadItem = new FileDownloadItem();
    this.commonApiService
      .fileTalkDownload(
        {
          userSeq: this.userSeq,
          deviceType: this.deviceType,
          token: this.token,
          attachmentsSeq: this.fileInfo.attachmentSeq,
          fileDownloadItem: this.fileDownloadItem
        },
        this.downloadUrl
      )
      .pipe(
        take(1),
        map(async rawBlob => {
          const blob = rawBlob.slice(
            0,
            rawBlob.size,
            MimeUtil.getMimeFromExtension(this.fileInfo.fileExt)
          );

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

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