import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Events } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup } from "@angular/forms";
import { Http } from '@angular/http'
import { dialcode } from "../../models/mymodel";
import { OrderbyPipe } from '../../providers/sort-pipe';
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-myprofile',
  templateUrl: 'myprofile.html',
})
export class MyprofilePage {
  editForm: FormGroup
  imagechange: boolean = false;
  fileUri: any;
  local:driver;
  formdata = new FormData();
  codes: Array<dialcode>;
  cars:any;
  maxDate:any;

  constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, private http: Http, private orderbyPipe: OrderbyPipe, private myservice: Myservice, private storage: Storage, public events: Events, private toast: Toast) {
    
    this.maxDate = new Date().getFullYear()

    this.editForm = this.formBuilder.group({
      name: ['', Validators.compose([Validators.required, Validators.minLength(3)])],
      username: ['', Validators.compose([Validators.required, Validators.minLength(3)])],
      email: ['', Validators.compose([Validators.required, Validators.pattern("[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}")])],
      dial_code: ['', Validators.required],
      phone: ['', Validators.compose([Validators.required, this.myservice.checkLimit(10000000, 999999999999999)])],
      image:[''],
      secret_key: ['My_key'],
      license:['',Validators.required],
      cartype:['',Validators.required],
      car_no:['',Validators.required],
      dob:['',Validators.required],
      gender:['',Validators.required],
    })

    this.http.get('dial-codes.json')
      .subscribe(response => {
        this.codes = response.json().dialCodes
        this.codes = this.orderbyPipe.transform(this.codes, 'dialCode');
      })
  }

  ionViewDidEnter() {
    this.storage.get('driver_data').then(data=>{
      if(data){
        this.local = data;
        this.myservice.load_post({id:data.id}, 'getdriverDetails').subscribe(resp => {
          if (resp.status == 'success') {
            this.editForm.controls['name'].setValue(resp.data.name)
            this.editForm.controls['username'].setValue(resp.data.user_name)
            this.editForm.controls['email'].setValue(resp.data.email)
            this.editForm.controls['dial_code'].setValue(resp.data.dial_code)
            this.editForm.controls['phone'].setValue(resp.data.phone)
            this.editForm.controls['image'].setValue(this.myservice.base_url+resp.data.image)
            this.editForm.controls['car_no'].setValue(resp.data.car_no)
            this.editForm.controls['cartype'].setValue(resp.data.car_type)
            this.editForm.controls['dob'].setValue(resp.data.dob)
            this.editForm.controls['gender'].setValue(resp.data.gender)
            this.editForm.controls['license'].setValue(resp.data.license_no)
          }
        })
      }
    })
    this.myservice.load_post({},'getCarTypes').subscribe(resp=>{
      if(resp.status == 'success'){
        this.cars = resp.data
      }
    })
  }

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

      var reader = new FileReader();

      reader.onload = (event: any) => {
        this.editForm.controls['image'].setValue(event.target.result)
      }

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

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

  updateProfile(){
    this.myservice.show_loader()
    this.formdata.append('data', JSON.stringify(this.editForm.value));
    this.formdata.append('id', JSON.stringify(this.local.id));
    this.myservice.fileUpload(this.formdata, 'updatedriverProfile').subscribe(response => {
      this.myservice.hide_loader()
      if (response.status == 'success') {
        this.local = response.data
        if (this.imagechange == true){
          this.local.image = this.local.image.startsWith("http") ? this.local.image : this.myservice.base_url + this.local.image;
        }

        this.events.publish('driver:profile', this.local);

          this.toast.show(response.message, '2000', 'center').subscribe(toast => {
            console.log(toast);
          });
          
        }
        else {
          this.myservice.show_alert('', response.message)
        }
    })
  }

}
