import { RemoteFileStorage } from './../../services/file-storage-service';
import { Router } from 'aurelia-router';
import { FilePreviewer } from '../../resources/elements/previewers/file-previewer';
import { DialogService } from 'aurelia-dialog';
import { Config } from '../../config';
import * as ExifReader from 'exifreader';
import { autoinject, singleton } from 'aurelia-framework';
import { HttpClient, json } from 'aurelia-fetch-client';
import breeze from 'breeze-client';

export type PictureOrientation = "Landscape" | "Portrait";

export declare interface PictureType {
  url: string;
  previewUrl?: string;
  contentTypeId: number;
  isSelected: boolean;
  orientation: string;
}


@autoinject
@singleton(false)
export class PictureHelper {
  constructor(private router: Router, private httpClient: HttpClient, private config: Config, private dialogService: DialogService, private fileStorageService: RemoteFileStorage.Service) {
  }

  public detectionOrientation(reader: FileReader): boolean {
    let isPortrait = false;
    try {
      const tags = ExifReader.load(reader.result as ArrayBuffer);

      let orientationTag = tags["Orientation"];
      let orientationVal = (orientationTag != null) ? orientationTag.value : null;

      if (orientationTag == null || (orientationVal != null && orientationVal == 1)) {
        let height = tags["Image Height"].value;
        let width = tags["Image Width"].value;
        if (height >= width) {
          isPortrait = true;
        }
      }
      else {
        if (orientationVal == 6 || orientationVal == 8 || orientationVal == 5 || orientationVal == 7) {
          isPortrait = true;
        }
      }
    }
    catch (error) {
      console.log("It seems that this image do not contains any exif metadata");
    }
    return isPortrait;
  }

  public async rotatePicture(clockwise: boolean, pictureEntity: (PictureType & breeze.Entity)) {
    let saveUri = pictureEntity.url;

    let newFileUrl = await this.fileStorageService.rotate(saveUri, clockwise);
    if (newFileUrl != null) {
      pictureEntity.url = newFileUrl;
      pictureEntity.orientation = pictureEntity.orientation == "Landscape" ? "Portrait" : "Landscape";
    }
    else {
      pictureEntity.url = saveUri;
    }
  }

  public previewFile(fileEntity: { url: string, name?: string }, isBlob: boolean = false) {
    if (fileEntity.url != null) {
      var fileExtension: string = this.getFileExtension(fileEntity.url);
      this.dialogService.open({
        viewModel: FilePreviewer,
        model: { fileExtension: fileExtension, fileUrl: fileEntity.url, fileName: fileEntity.name, isBlob: isBlob },
        lock: false,
        position(dialogContainer, dialogOverlay) {
          dialogContainer.classList.add("file-previewer-container");
          dialogOverlay.classList.add("file-previewer-container");
        }
      });
    }
  }

  public getFileExtension(fileUrl: string): string {
    let fileExtension: string;
    if (fileUrl != null && fileUrl.length > 0) {
      fileExtension = fileUrl.split('.').pop().toLowerCase();
      switch (fileExtension) {
        case "jpeg": {
          fileExtension = "jpg";
          break;
        }
        case "xls": {
          fileExtension = "xlsx";
          break;
        }
        case "pptx": {
          fileExtension = "ppt";
          break;
        }
      }
    }
    return fileExtension;
  }

  public getFileType(fileUrl: string): string {
    return "digi-" + this.getFileExtension(fileUrl) + "-file";
  }

  public async downloadFile(fileEntity: { url: string, name?: string }) {
    if (this.fileStorageService.secure) {
      this.fileStorageService.download(fileEntity.url);
      //@todo: support local storage
    } 
    else 
    {// Legacy mode
      if (fileEntity.url.startsWith(this.config.globalConfig.remoteServiceName)) {
        let link = document.createElement('a');
        link.href = fileEntity.url;
        link.download = fileEntity.name || fileEntity.url.substring(fileEntity.url.lastIndexOf('/') + 1)
        link.click();
      } else {
        this.router.navigate(fileEntity.url, { replace: false });
      }
    }
  }

  public static getFileNameWithoutExtension(fileName: string) {
    return fileName.substring(0, fileName.lastIndexOf('.'));
  }

  public static getFileExtension(fileName: string) {
    return fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
  }
}
