import { AfterViewInit, Component, Input, OnInit } from '@angular/core';
import { marker } from '@biesbjerg/ngx-translate-extract-marker';
import { DriveFile } from 'src/app/components/resource-page/drive-window/drive-layout/drive-file';
import { NanoService } from 'src/app/shared/nano/nano.service';
import { RoomRecord } from 'src/app/shared/server-services/query-records/room-records';
import { RoomService } from 'src/app/shared/server-services/room.service';
import { ServerError } from 'src/app/shared/server-services/server-errors';
import { DialogService } from 'src/app/shared/services/dialog.service';
import {
  DownloadManagerService,
  FileManagerType,
} from 'src/app/shared/services/download-manager-service';
import { RouterHandler } from 'src/app/shared/services/router-handler.service';
import { isNanoFeatureSupported, NanoFeature } from 'src/app/shared/drive-version';
import { MediaViewerService } from 'src/app/shared/media-viewer/media-viewer.service';
import { BlobService } from 'src/app/shared/services/blob.service';
import { SnackBarService } from 'src/app/shared/services/snackbar.service';

export type AttachedFileUrl = {
  file: string;
  path: string;
  roomId: string;
};

@Component({
  selector: 'app-markdown-file-preview',
  templateUrl: './markdown-file-preview.component.html',
  styleUrls: ['./markdown-file-preview.component.scss'],
})
export class MarkdownFilePreviewComponent implements OnInit {
  @Input() fileUrl: AttachedFileUrl;
  public file: DriveFile;
  public roomData: RoomRecord;
  public isLoaded: boolean = false; // load the file info from nano
  public isFileValid: boolean;
  public fileCheckError: boolean = false;
  private isDownloadStarted: boolean = false;
  public downloadProgress: number = 0;
  public isDir: boolean = false;
  // thumbnail response from the server
  public img0: Blob;

  constructor(
    private roomService: RoomService,
    private nanoService: NanoService,
    private routerHandler: RouterHandler,
    private downloadManagerService: DownloadManagerService,
    private dialogService: DialogService,
    private mediaViewerService: MediaViewerService,
    private blobService: BlobService,
    private snackbarService: SnackBarService
  ) {}

  ngOnInit(): void {
    console.log('fileUrl', this.fileUrl);

    this.file = new DriveFile({
      name: this.fileUrl.file,
      size: 0,
      mtime: 0,
    });

    this.roomService.getRoom(this.fileUrl.roomId).then((roomData) => {
      this.roomData = roomData;

      this.roomService.getNanoSession(roomData.id).then((nanoSession) => {
        if (nanoSession && isNanoFeatureSupported(nanoSession.version, NanoFeature.PEEK)) {
          this.nanoService.peekFile(
            this.fileUrl.roomId,
            (this.fileUrl.path ? this.fileUrl.path + '/' : '') + this.fileUrl.file,
            (file) => {
              this.file = new DriveFile(file);
              this.isLoaded = true;
              this.isFileValid = true;
              this.isDir = this.file.ext == 'dir';
              if (file.img0) this.img0 = this.blobService.new([file.img0.buffer]);
              //console.log("Peek file", file);
            },
            (err) => {
              if (err.error == ServerError.NANO_REQUEST_ERROR_HANDLER_TARGET_NOT_FOUND) {
                this.isLoaded = true;
                this.isFileValid = false;
              } else {
                this.fileCheckError = true;
                this.isLoaded = true;
              }
              console.error('err', err);
            }
          );
        }
      });
    });
  }

  public openPath() {
    let fragment = this.routerHandler.getRoute().fragment;

    if (this.isDir) {
      fragment['path'] = this.fileUrl.path + '/' + this.file.name;
    } else {
      if (this.fileUrl.path) {
        fragment['path'] = this.fileUrl.path;
      }
      fragment['file'] = this.fileUrl.file;
    }

    this.routerHandler.navigate(['/room/', this.fileUrl.roomId, 'drive'], {
      fragment: this.routerHandler.fragmentToRaw(fragment),
    });
  }

  public openFile() {
    if (this.file.mime.startsWith('image')) {
      let path = this.file.fullName;
      if (this.fileUrl.path.length > 0) {
        path = this.fileUrl.path + '/' + path;
      }
      this.mediaViewerService.showImage(this.roomData.id, path, this.file);
    } /*else if (
      this.file.mime == "application/pdf"
    ) {
      this.mediaViewerService.showPdf(
        this.roomData.id,
        this.fileUrl.path + "/" + this.file.fullName,
        this.file
      );
    }*/
  }

  public download() {
    if (!this.isDownloadStarted) {
      this.isDownloadStarted = true;
      this.downloadManagerService
        .download(
          this.fileUrl.roomId,
          (this.fileUrl.path ? this.fileUrl.path + '/' : '') + this.fileUrl.file,
          this.file,
          (curr, max, speed, timeNeeded, refForFile: FileManagerType) => {
            if (max > 0) {
              this.downloadProgress = (curr / max) * 100;
            }
          }
        )
        .then(() => {})
        .catch(() => {
          this.dialogService.openAlertDialog(
            marker('Error'),
            marker('Error happened during the file download')
          );
        })
        .finally(() => {
          this.isDownloadStarted = false;
        });
    } else {
      this.snackbarService.showSnackbar(marker('Download already started!'));
    }
  }
}
