import { Component, Input, OnDestroy, OnInit } from "@angular/core";
import {
  DownloadManagerService,
  FileManagerDirection,
  FileManagerType,
} from "../../../shared/services/download-manager-service";
import { NanoService } from "../../../shared/nano/nano.service";
import { RoomService } from "src/app/shared/server-services/room.service";
import { RoomRecord } from "src/app/shared/server-services/query-records/room-records";
import { RouterHandler } from "src/app/shared/services/router-handler.service";
import { DialogService } from "src/app/shared/services/dialog.service";
import { marker } from "@biesbjerg/ngx-translate-extract-marker";
import { DomSanitizer } from "@angular/platform-browser";

@Component({
  selector: "app-download-manager-file",
  templateUrl: "./download-manager-file.component.html",
  styleUrls: ["./download-manager-file.component.scss"],
})
export class DownloadManagerFileComponent implements OnInit, OnDestroy {
  @Input("file") file: FileManagerType;
  public chunkSizeM;
  public isPaused: boolean = false;
  public roomData: RoomRecord;
  public canShowAsImage: boolean = false;
  public showPreview: boolean = false;
  public safeBlobURL;
  // for browser file from computer; do not forget to revoke
  // created only, when toggleView is triggered
  private fileObjectURL; 

  constructor(
    private nanoService: NanoService,
    private roomService: RoomService,
    private routerHandler: RouterHandler,
    private downloadManagerService: DownloadManagerService,
    private dialogService: DialogService,
    private sanitizer: DomSanitizer
  ) {
    this.chunkSizeM = NanoService.NETWORK_FILE_CHUNK_SIZE;
  }

  ngOnInit(): void {
    this.roomService.getData(this.file.resourceId).then((data) => {
      this.roomData = data;
    });
    
    if (
      ["bmp", "gif", "ico", "jpeg", "jpg", "png"].includes(this.file.file.ext)
    ) {
      this.canShowAsImage = true;
    }
  }

  ngOnDestroy(){
    if (this.fileObjectURL){
      URL.revokeObjectURL(this.fileObjectURL);
    }
  }

  public toggleViewer() {
    this.showPreview = !this.showPreview;
    if (this.showPreview) {
      if (this.file.direction == FileManagerDirection.UP){
        this.fileObjectURL = URL.createObjectURL(<File>this.file.file.rawData)
        this.safeBlobURL = this.sanitizer.bypassSecurityTrustUrl(
          this.fileObjectURL
        );
      }
      else{
        this.safeBlobURL = this.sanitizer.bypassSecurityTrustUrl(
          this.file.objectURL
        );
      }
    }
  }

  public pause() {
    if (!this.isPaused) {
      this.isPaused = true;
      if (this.file.direction == FileManagerDirection.UP) {
        this.nanoService.pauseUploadSession(this.file.requestId);
      } else {
        this.nanoService.pauseRequest(this.file.requestId);
      }
    }
  }

  /**
   * stored blob can be redownload for a short time, if
   * you accidentally denied or cancel the download popup
   */
  public redownload() {
    var a;
    a = document.createElement("a");
    a.href = this.file.objectURL;
    a.download = this.file.file.fullName;
    //document.body.appendChild(a);
    //a.style = "display: none";
    a.click();
    //a.remove();
  }

  public resume() {
    if (this.isPaused) {
      this.isPaused = false;
      if (this.file.direction == FileManagerDirection.UP) {
        this.nanoService.resumeUploadSession(this.file.requestId);
      } else {
        this.nanoService.resumeRequest(this.file.requestId);
      }
    }
  }

  public remove() {
    if (!this.file.done && this.file.currPart > 100) {
      console.log("file", this.file);
      // this file is already downloaded more than 50 M, ask if the user is sure about to delete
      this.dialogService
        .openConfirmDialog(
          marker("Remove downloading file"),
          marker("Are you sure you want to stop the file progress?") +
            "( " +
            this.file.file.fullName +
            " )"
        )
        .subscribe((response) => {
          if (response) {
            this.downloadManagerService.remove(this.file);
          }
        });
    } else {
      this.downloadManagerService.remove(this.file);
    }
  }

  public openPath() {
    if(this.isUploading) return;

    let fragment = this.routerHandler.getRoute().fragment;
    fragment["path"] = this.file.path.split("/").slice(0, -1).join("/");
    fragment["file"] = this.file.file.fullName;

    this.routerHandler.navigate(["/room/", this.file.resourceId, "drive"], {
      fragment: this.routerHandler.fragmentToRaw(fragment),
    });
  }

  get isUploading(): boolean{
    return !this.file.done && this.file.direction == "up";
  }
}
