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';

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

  constructor(public navCtrl: NavController, public navParams: NavParams, private myservice: Myservice, private storage: Storage, private toast: Toast) {
  }

  ionViewDidEnter() {
    this.storage.get('driver_data').then(data => {
      if (data) {
        this.local = data
        this.myData.id = data.id
        this.myservice.load_post({ id: data.id, field: this.title }, 'getDocument').subscribe(response => {
          this.myservice.hide_loader()
          if (response.status == 'success') {
            document.getElementById("upld_btn").textContent = 'UPDATE'
            this.fileData = response.data
          }
          else
            document.getElementById("upld_btn").textContent = '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() {
    this.myservice.show_loader()
    this.formdata.append('data', JSON.stringify(this.myData));
    if (this.fileData)
      this.formdata.append('id', JSON.stringify(this.fileData.id));

    this.myservice.fileUpload(this.formdata, 'driverDocUpload').subscribe(resp => {
      this.myservice.hide_loader()
      if (resp.status == 'success') {
        // this.toast.show(response.message, '2000', 'center').subscribe(toast => {
          //   console.log(toast);
          // });
      }
      else
        this.myservice.show_alert('', resp.message);
    })
  }

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


}
