import { Component, OnInit, Input, Output, EventEmitter, NgZone } from "@angular/core";
import { CommonService } from "src/app/hmg-common/services/common/common.service";
import { TranslatorService } from "src/app/hmg-common/services/translator/translator.service";
import { AlertController, ActionSheetController, Platform } from "@ionic/angular";
import {
  Camera,
  CameraOptions,
  PictureSourceType
} from "@ionic-native/Camera/ngx";
import { FileChooser } from "@ionic-native/file-chooser/ngx";
import { File } from "@ionic-native/file/ngx";
import { FilePath } from "@ionic-native/file-path/ngx";
import { Base64 } from "@ionic-native/base64/ngx";
import { IOSFilePicker } from '@ionic-native/file-picker/ngx';
import { Location } from '@angular/common';
import { DomSanitizer, SafeUrl } from "@angular/platform-browser";


@Component({
  selector: "file-uploader",
  templateUrl: "./file-uploader.component.html",
  styleUrls: ["./file-uploader.component.scss"]
})
export class FileUploaderComponent implements OnInit {
  @Input() multiupload = false;
  @Input() attachmentname = "attachment-loader";
  public attachmentData: string;
  public errorMsg: string;
  public selectedOpn: number = 1;
  public allowdType: any = ["jpg", "jpeg", "png", "gif", "pdf", "doc", "docx"];
  @Input() maxFileSize = 5 * 1024 * 1024;
  @Output() fileSelected = new EventEmitter();
  public inputFiles: any = [];
  public attachmentImg = "assets/icon/attachment.png";
  public deleteImg = "assets/icon/delete.png";
  public nativePath: any;
  public actionSheet: any;
  public isActionSheetShown: boolean = false;
  @Input() selectedAttachment = [];
  constructor(
    public cs: CommonService,
    public ts: TranslatorService,
    public alertController: AlertController,
    private cameraController: Camera,
    private actionSheetController: ActionSheetController,
    private fileChooser: FileChooser,
    private file: File,
    private filePath: FilePath,
    public base64: Base64,
    public platform: Platform,
    private iOSfilePicker: IOSFilePicker,
    public ngzone: NgZone,
    public loc: Location,
    public sanitizer: DomSanitizer
  ) { }

  ngOnInit() {
    this.platform.backButton.subscribeWithPriority(9999, () => {
      // You decide what happens 
      if (this.isActionSheetShown)
        this.actionSheet.dismiss();
      else
        this.loc.back();
    });
    this.inputFiles = this.selectedAttachment;
  }

  ngOnDestroy(): void {
  }
  async openFile() {
    if (this.platform.is('ios'))
      this.openiOSActionSheet();
    else
      this.openAndroidActionSheet();
    //this.openiOSActionSheet();

  }
  async openAndroidActionSheet() {
    this.actionSheet = await this.actionSheetController.create({
      header: this.ts.trPK("itemforsale", "slect-source-file"), //"Select Image file",

      buttons: [
        {
          text: this.ts.trPK("itemforsale", "from-library"),
          handler: () => {
            this.takePictureiOS();
          }
        },
        {
          text: this.ts.trPK("itemforsale", "from-camera"),
          handler: () => {
            this.takePicture(this.cameraController.PictureSourceType.CAMERA);
          }
        },
        {
          text: this.ts.trPK("general", "cancel"),
          role: "cancel"
        }
      ]
    });
    this.isActionSheetShown = true;
    await this.actionSheet.present();
  }

  async openiOSActionSheet() {
    this.actionSheet = await this.actionSheetController.create({
      header: this.ts.trPK("itemforsale", "slect-source-file"), //"Select Image file",
      buttons: [
        {
          text: this.ts.trPK("itemforsale", "from-library"),
          handler: () => {
            this.takePictureiOS();
          }
        },
        {
          text: this.ts.trPK("itemforsale", "from-camera"),
          handler: () => {
            this.takePicture(this.cameraController.PictureSourceType.CAMERA);
          }
        },

        {
          text: this.ts.trPK("itemforsale", "from-icloud"),
          handler: () => {
            this.takePicture(this.cameraController.PictureSourceType.PHOTOLIBRARY);
          }
        },
        {
          text: this.ts.trPK("general", "cancel"),
          role: "cancel"
        }
      ]
    });
    this.isActionSheetShown = true;
    await this.actionSheet.present();
  }

  public takePictureiOS() {
    const options: CameraOptions = {
      quality: 60,
      sourceType: this.cameraController.PictureSourceType.PHOTOLIBRARY,
      destinationType: this.cameraController.DestinationType.DATA_URL,
      encodingType: this.cameraController.EncodingType.JPEG,
      mediaType: this.cameraController.MediaType.PICTURE,
      correctOrientation: true,
    }
    this.cameraController.getPicture(options).then((imageData) => {
      const data = "data:image/jpeg;base64," + imageData;
      this.pushFiles(this.getFileName(), data);
    }, (err) => {
    });
  }

  public deleteFiles(index: number) {
    this.inputFiles.splice(index, 1);
    this.fileSelected.emit({
      name: null,
      data: "",
      inputFiles: this.inputFiles
    });
    this.errorMsg = null;
  }
  public switchOptions($event) {
    this.selectedOpn = $event;
  }
  public takePicture(sourceType: PictureSourceType) {
    const options: CameraOptions = {
      quality: 50,
      destinationType: this.cameraController.DestinationType.DATA_URL,
      encodingType: this.cameraController.EncodingType.JPEG,
      sourceType: sourceType,
      mediaType: this.cameraController.MediaType.PICTURE,
      correctOrientation: true
    };
    if (sourceType === this.cameraController.PictureSourceType.PHOTOLIBRARY) {
      if (this.platform.is('android')) {
        this.fileChooser
          .open()
          .then(uri => {
            this.readFile(uri);
          })
          .catch(e => { });
      } else {
        this.iOSfilePicker.pickFile(['public.content']).then(uri => {

          let correctPath = uri.substr(0, uri.lastIndexOf('/') + 1);
          let currentName = uri.substring(uri.lastIndexOf('/') + 1);
          this.nativePath = uri;

          this.file.readAsDataURL("file:///" + correctPath, currentName).then(result => {
            this.pushFiles(currentName, result);
          }).catch(e => { });
        }).catch(e => { });
      }
    } else {
      this.cameraController.getPicture(options).then(imageData => {
        const data = "data:image/jpeg;base64," + imageData;
        this.pushFiles(this.getFileName(), data);
      });
    }
  }
  pushFiles(name, files) {
    this.ngzone.run(() => {
      if (this.multiupload) {
        this.inputFiles.push({ name: name, data: files });
      } else {
        this.inputFiles = [{ name: name, data: files }];
      }
      this.fileSelected.emit({
        name: name,
        data: files,
        inputFiles: this.inputFiles
      });
    });
  }
  readFile(fileUrl: any) {
    this.filePath.resolveNativePath(fileUrl).then(filePathResult => {
      this.nativePath = filePathResult;
      this.file.resolveLocalFilesystemUrl(this.nativePath).then(entry => {
        entry.getMetadata(metadata => {
          if (metadata.size <= this.maxFileSize) {
            this.errorMsg = null;
            this.encodeFiles(entry);
          } else {
            this.errorMsg = this.ts.trPK("general", "large-file");
          }
        }, (error) => {
          console.log(error)
        });
      });
    });
  }
  getImgContent(imgFile): SafeUrl {
    console.log(imgFile);
    return this.sanitizer.bypassSecurityTrustUrl(imgFile);
  }

  checkDuplicate(name: string) {
    return this.inputFiles.filter(a => {
      return a.name === name;
    });
  }
  encodeFiles(entry) {
    let fileName = entry.nativeURL.split('/').pop();
    let path = entry.nativeURL.substring(0, entry.nativeURL.lastIndexOf("/") + 1);

    this.file.readAsDataURL(path, fileName)
      .then(base64File => {
      })
      .catch((err) => {
        console.log('Error reading file', err);
      })
    this.base64.encodeFile(this.nativePath).then(
      (base64File: string) => {
        const type = this.nativePath.substr(
          this.nativePath.lastIndexOf(".") + 1
        );
        if (this.allowdType.includes(type.toLowerCase())) {
          if (this.checkDuplicate(entry.name).length === 0) {
            this.pushFiles(entry.name, base64File);
            this.errorMsg = null;
          } else {
            this.errorMsg = this.ts.trPK("general", "file-name-exist");
          }
        } else {
          this.attachmentData = null;
          this.errorMsg = this.ts.trPK("general", "not-supported");
        }
      },
      err => {
        console.log(err);
      }
    );
  }
  getFileName() {
    const date = new Date().valueOf();
    let text = "";
    const possibleText =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (let i = 0; i < 5; i++) {
      text += possibleText.charAt(
        Math.floor(Math.random() * possibleText.length)
      );
    }
    const imageName = date + "." + text + ".jpeg";
    return imageName;
  }
}
