import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Myservice } from "../../providers/myservice";
import { Storage } from "@ionic/storage";
import { driver } from "../../models/mymodel";
import { Toast } from '@ionic-native/toast';
import { dataService } from "../../providers/common.service";
import { PhotoViewer } from '@ionic-native/photo-viewer';
import { FileOpener } from '@ionic-native/file-opener';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';

@IonicPage()
@Component({
  selector: 'page-docupdate',
  templateUrl: 'docupdate.html',
})
export class DocupdatePage {
  title: string = this.navParams.get('title')
  formdata = new FormData();
  filename: string;
  local: driver;
  fileData: any;
  baseUrl: string = this.myservice.base_url
  myData = { 'secret_key': 'My_key' }
  butonName:string;

  constructor(public navCtrl: NavController, public navParams: NavParams, private myservice: Myservice, private storage: Storage, private toast: Toast, private comService: dataService, private photoViewer: PhotoViewer, private fileOpener: FileOpener, private transfer: FileTransfer, private file: File) {
  }

  ionViewDidEnter() {
    this.fileData = this.comService.getdocData();

    console.log(this.fileData)
    this.storage.get('driver_data').then(data => {
      if (data) {
        this.myservice.hide_loader()
        this.local = data
        
        if (this.fileData.fileStatus == '3') {
          this.butonName = 'UPDATE'
        }
        else if (this.fileData.fileStatus == '0') {
          this.butonName = 'UPLOAD'
        }
      }
    })
  }

  fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {

      var reader = new FileReader();

      reader.readAsDataURL(event.target.files[0]);

      let file = fileList[0];
      var ext = (file.name).split(".").pop();
      if (ext == 'jpg' || ext == 'jpeg' || ext == 'png' || ext == 'pdf') {
        this.filename = file.name
        this.formdata.append('image', file, file.name);
      }
      else {
        this.myservice.show_alert('', 'Please choose file with .jpg/.jpeg/.png/.pdf extension')
      }
    }
  }

    upload() {
    if (this.filename) {
      this.myservice.show_loader()
      this.formdata.append('data', JSON.stringify(this.myData));
      if (this.fileData)
        this.formdata.append('id', JSON.stringify(this.fileData.fileId));

      this.myservice.fileUpload(this.formdata, 'driverDocUpload').subscribe(resp => {
        this.myservice.hide_loader()
        if (resp.status == 'success') {
          this.navCtrl.pop();
          this.toast.show(resp.message, '2000', 'center').subscribe(toast => {
              console.log(toast);
            });
        }
        else
          this.myservice.show_alert('', resp.message);
      })
    }
    else
    this.myservice.show_alert('','Please select a file to upload')
  }

  view() {
    if (this.fileData.image.includes(".pdf")) {

      console.log(this.baseUrl + this.fileData.image)

      const fileTransfer: FileTransferObject = this.transfer.create();
      const url = this.baseUrl + this.fileData.image;
      fileTransfer.download(url, this.file.dataDirectory + 'files.pdf').then((entry) => {
        console.log('download complete: ' + entry.toURL());

        this.fileOpener.open(entry.toURL(), 'application/pdf')
          .then(() => console.log('File is opened'))
          .catch(e => console.log('Error openening file', e));
      }, (error) => {
        // handle error
        console.log(error)
      });
      // this.document.viewDocument(this.baseUrl + this.fileData.image, 'application/pdf', options) //document viewer plugin
    }
    else {
      this.photoViewer.show(this.baseUrl + this.fileData.image);
    }
  }

  back() {
    this.navCtrl.pop();
  }


}
