import { Router } from 'aurelia-router';
import { autoinject, bindable, computedFrom } from 'aurelia-framework';
import { DialogController } from "aurelia-dialog";
import { Extensions } from '../../../constants/constants';
import { Config } from '../../../config';

export type FilePreviewerModel = { fileExtension: string, fileUrl: string, fileName?: string };
@autoinject
export class OldFilePreviewer {
  @bindable
  protected loadTimeout = 1000;
  protected iframeRef: HTMLIFrameElement;
  protected originalUrl: string;
  protected fileName: string
  protected model: FilePreviewerModel
  protected timer: NodeJS.Timeout;
  protected isLoading = true;

  constructor(protected dialogController: DialogController, protected router: Router, protected config: Config) { }

  public activate(model: FilePreviewerModel) {
    this.model = model;
    this.originalUrl = model.fileUrl;
  }

  public attached() {
    if (this.iframeRef != null) {
      this.iframeRef.onload = () => {
        this.markIframeLoaded();
      }

      this.loadIframe();
    }
    this.fileName = this.model.fileUrl.split('/').last();
  }

  public detached() {
    clearTimeout(this.timer);
  }

  protected loadIframe() {
    this.isLoading = true;
    this.timer = setTimeout(() => {
      this.loadIframe();
    }, this.loadTimeout)

    try {
      this.iframeRef.src = this.getUrlFrame();
    } catch (e) {
      // Google docs viewer sometimes sends an error when displaying.
      // Catch this and mark as loaded
      this.markIframeLoaded();
    }
  }

  private markIframeLoaded() {
    this.isLoading = false;
    clearTimeout(this.timer);
  }

  @computedFrom("model.fileExtension")
  protected get isPictureOrGif() {
    return Extensions.picture.includes(this.model.fileExtension) || this.model.fileExtension == 'gif'
  }
  @computedFrom("model.fileExtension")
  protected get isOther() {
    return Extensions.other.includes(this.model.fileExtension)
  }
  @computedFrom("model.fileExtension")
  protected get isOffice() {
    return Extensions.office.includes(this.model.fileExtension)
  }
  @computedFrom('isOffice', 'isPictureOrGif', 'isOther', 'isFromLocalStorage')
  protected get isNotSupported() {
    if (this.isFromLocalStorage) {
      return false == (this.isPictureOrGif || this.isOther);
    }
    return false == (this.isOffice || this.isPictureOrGif || this.isOther)
  }
  @computedFrom('originalUrl')
  protected get isFromLocalStorage() {
    return this.originalUrl.startsWith(this.config.globalConfig.remoteServiceName);
  }

  protected getUrlFrame(): string {
    if (this.isNotSupported) {
      return '';
    }
    if (this.isFromLocalStorage) {
      // PDF, Txt and images can be shown
      return this.originalUrl;
    }
    if (this.isOffice || this.isOther) {
      //Trick to force embeded previewer to read the given url every time (Used if url is same but content has changed since)
      let fileUrl = new URL(this.model.fileUrl);
      fileUrl.searchParams.append("dt", new Date().toISOString());
      if (this.isOffice) {
        return `https://view.officeapps.live.com/op/embed.aspx?src=${fileUrl.href}`;
      }
      else {
        return `https://docs.google.com/viewerng/viewer?url=${fileUrl.href}&embedded=true`;
      }
    }
    return '';
  }

  public download() {
    if (this.isFromLocalStorage) {
      let link = document.createElement('a');
      link.href = this.originalUrl;
      link.download = this.model.fileName || this.originalUrl.substring(this.originalUrl.lastIndexOf('/') + 1)
      link.click();
    } else {
      this.router.navigate(this.originalUrl, { replace: false });
    }
  }
}
