import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { MatBottomSheet } from '@angular/material/bottom-sheet';
import { DomSanitizer } from '@angular/platform-browser';
import { marker } from '@biesbjerg/ngx-translate-extract-marker';
import { RoomRecord } from 'src/app/shared/server-services/query-records/room-records';
import { RoomService } from 'src/app/shared/server-services/room.service';
import { BlobService } from 'src/app/shared/services/blob.service';
import { CordovaService } from 'src/app/shared/services/cordova.service';
import { DialogService } from 'src/app/shared/services/dialog.service';
import { RouterHandler } from 'src/app/shared/services/router-handler.service';
import { NanoService } from '../../../shared/nano/nano.service';
import {
  DownloadManagerService,
  FileManagerDirection,
  FileManagerType,
} from '../../../shared/services/download-manager-service';
import { scrollToFileObserver } from '../../resource-page/drive-window/drive-layout/drive-layout.component';

@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: FileManagerType;
  public chunkSizeM;
  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;
  public isOnApp: boolean = false;

  constructor(
    private nanoService: NanoService,
    private roomService: RoomService,
    private routerHandler: RouterHandler,
    private downloadManagerService: DownloadManagerService,
    private dialogService: DialogService,
    private sanitizer: DomSanitizer,
    private blobService: BlobService,
    private cordovaService: CordovaService,

    private bottomSheet: MatBottomSheet
  ) {
    this.chunkSizeM = NanoService.NETWORK_FILE_CHUNK_SIZE;
    this.isOnApp = cordovaService.isOnApp();
  }

  ngOnInit(): void {
    this.roomService.getRoom(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) {
      this.blobService.revokeObjectURL(this.fileObjectURL);
    }
  }

  public toggleViewer() {
    this.showPreview = !this.showPreview;
    if (this.showPreview) {
      if (this.file.direction == FileManagerDirection.UP) {
        this.fileObjectURL = this.blobService.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.file.paused) {
      this.file.paused = true;
      this.cordovaService.isOnApp() &&
        this.cordovaService.removeRunningProcess(this.file.requestId);
      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.file.paused) {
      this.file.paused = false;
      this.cordovaService.isOnApp() &&
        this.cordovaService.registerRunningProcess(this.file.requestId);
      if (this.file.direction == FileManagerDirection.UP) {
        this.nanoService.resumeUploadSession(this.file.requestId);
      } else {
        this.nanoService.resumeRequest(this.file.requestId);
      }
    }
  }

  public open() {
    this.cordovaService.open(this.file.mobileLocalPath + '/' + this.file.file.fullName);
  }

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

    //removing error file, must remove error notification too
    if (this.cordovaService.isOnApp() && this.file.error) {
      this.cordovaService.clearNotification(CordovaService.PROGRESS_ERROR_NOTIFICATION_ID);
    }
  }

  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;

    if (fragment?.['from']) {
      delete fragment['from'];
    }

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

    if (this.file?.file?.fullName) {
      scrollToFileObserver.next(this.file.file.fullName);
    }

    this.bottomSheet.dismiss();
  }

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