import { Component, HostListener, OnDestroy } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { marker } from '@biesbjerg/ngx-translate-extract-marker';
import { Subscription } from 'rxjs';
import { DriveFile } from 'src/app/components/resource-page/drive-window/drive-layout/drive-file';
import { NanoService, RequestSession } from '../../nano/nano.service';
import { BlobService } from '../../services/blob.service';
import { CordovaService } from '../../services/cordova.service';
import { DialogService } from '../../services/dialog.service';
import { SnackBarService } from '../../services/snackbar.service';
import { MediaViewerService } from '../media-viewer.service';

@Component({
  selector: 'app-pdf-viewer',
  templateUrl: './pdf-viewer.component.html',
  styleUrls: ['./pdf-viewer.component.scss'],
})
export class PdfViewerComponent implements OnDestroy {
  private sub: Subscription;
  public file: DriveFile;
  public currentChunk: number = 0;
  public maxChunk: number;
  public loaded: boolean = false;
  public data: Uint8Array;
  public objectURL: string;
  public safeUrl: SafeUrl;
  public opened: boolean = false;
  public error: boolean = false;
  private session: RequestSession;
  public thumbnailSafeUrl: SafeUrl;

  constructor(
    private mediaViewerService: MediaViewerService,
    private sanitizer: DomSanitizer,
    private cordovaService: CordovaService,
    private nanoService: NanoService,
    private blobService: BlobService,
    private snackbarService: SnackBarService,
    private dialogService: DialogService
  ) {
    this.sub = this.mediaViewerService.subscribePdfShow({
      next: (res) => {
        console.log('pdf');
        // init call
        this.reset(); // close the last session
        this.opened = true;
        this.file = res.file;

        this.thumbnailSafeUrl = this.sanitizer.bypassSecurityTrustUrl(
          this.blobService.createObjectURL(
            this.blobService.new([res.file.thumbnail]) // { type: res.file.mime }
          )
        );

        this.nanoService.getFile(
          res.roomId,
          res.path,
          null, // force to use the BlobSaver
          (response) => {
            this.data = response;
            this.objectURL = this.blobService.createObjectURL(
              this.blobService.new([this.data]) // , { type: "application/pdf" }
            );
            this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.objectURL);
            console.log('safeurl', this.safeUrl, this.objectURL);
            this.loaded = true;
            this.session = null;
          },
          (err) => {
            this.error = true;
            console.error('err', err);
          },
          (current, max, session) => {
            this.currentChunk = current;
            this.maxChunk = max;
          }
        );
      },
      error: (err) => {
        this.error = true;
        console.error('err', err);
      },
    });
  }

  ngOnDestroy(): void {
    if (this.sub) {
      this.sub.unsubscribe();
    }
  }

  private reset() {
    this.data = null;
    this.loaded = false;
    this.error = false;
    this.safeUrl = null;
    this.currentChunk = 0;
    this.maxChunk = 1;
    if (this.session) {
      this.session.pause();
      this.session = null;
    }
    if (this.objectURL) {
      this.blobService.revokeObjectURL(this.objectURL);
      this.objectURL = null;
    }
  }

  public close() {
    this.opened = false;
    this.reset();
  }

  public clickOutside(event) {
    // close when clicked on the background
    if (event.target && event.target.id == 'media-cont') {
      this.close();
    }
  }

  @HostListener('document:keydown.escape', ['$event']) onKeydownHandler(event: KeyboardEvent) {
    this.close();
  }

  public download() {
    console.log('this', this);
    if (this.cordovaService.isOnApp()) {
      this.cordovaService
        .getFileWriter(this.file.fullName)
        .then((fw) => {
          fw.write(this.data)
            .then(() => {
              this.snackbarService.showSnackbar(marker('Download is done'));
            })
            .catch((err) => {
              console.error('file save err', err);
              this.dialogService.openAlertDialog(
                marker('File save error'),
                marker('Could not save the file'),
                err
              );
            })
            .finally(() => {
              fw.close();
            });
        })
        .catch((err) => {
          console.error('file save creator err', err);
          this.dialogService.openAlertDialog(
            marker('File saver creator error'),
            marker('Could not save the file'),
            err
          );
        });
    } else {
      var a;
      a = document.createElement('a');
      a.href = this.objectURL;
      a.download = this.file.fullName;
      document.body.appendChild(a);
      a.style = 'display: none';
      a.click();
      a.remove();
    }
  }

  public zoom = 1;

  public zoomIn() {
    this.zoom += 0.2;
  }

  public zoomOut() {
    this.zoom -= 0.2;
  }
}
