import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,MenuController } 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';
import { TranslateService } from "@ngx-translate/core";

@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;
  lang: string = 'en';

  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, private translate: TranslateService,private menu:MenuController) {
  }

  ionViewDidEnter() {
    this.menu.swipeEnable(false)
    this.langTrans()
    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.translate.get(['docupdate.UPDATE']).subscribe(value => {
            this.butonName = value['docupdate.UPDATE']
          })
        }
        else if (this.fileData.fileStatus == '0') {
          this.translate.get(['docupdate.UPLOAD']).subscribe(value => {
            this.butonName = value['docupdate.UPLOAD']
          })
        }
      }
    })
  }

  langTrans() {
    this.storage.get('lang').then(lang => {
      if (lang != null) {
        this.translate.use(lang)
        this.lang = lang;
      }
      else {
        this.translate.use('en')
      }
    })
  }

  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.translate.get(['docupdate.Please choose file with .jpg/.jpeg/.png/.pdf extension']).subscribe(value => {
          this.myservice.show_alert('', value['docupdate.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.translate.get(['docupdate.' + resp.message]).subscribe(value => {
            this.toast.show(value['docupdate.' + resp.message], '2000', 'center').subscribe(toast => {
              console.log(toast);
            });
          })
        }
        else {
          this.translate.get(['docupdate.' + resp.message]).subscribe(value => {
            this.myservice.show_alert('', value['docupdate.' + resp.message])
          })
        }
      })
    }
    else{
      this.translate.get(['docupdate.Please select a file to upload']).subscribe(value => {
        this.myservice.show_alert('', value['docupdate.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();
  }

  ionViewWillLeave() {
    this.menu.swipeEnable(true)
  }

}
