import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FormGroup, Validators, FormBuilder } from '@angular/forms'
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-changepass',
  templateUrl: 'changepass.html',
})
export class ChangepassPage {
  pswdForm: FormGroup
  local: driver

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

    this.pswdForm = this.formbuilder.group({
      current: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
      new: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
      confirm: ['', Validators.compose([Validators.required]), this.MatchPassword.bind(this)],
      id: ['']
    })
  }

  ionViewDidEnter() {

    this.storage.get('driver_data').then(data => {
      if (data != null) {
        this.local = data
        this.pswdForm.controls['id'].setValue(this.local.id)
      }
    })
  }

  change() {
    this.myservice.show_loader();
    this.myservice.load_post(this.pswdForm.value, 'changePassword').subscribe(response => {
      this.myservice.hide_loader()
      if (response.status == 'success') {
        this.pswdForm.reset();
        // this.toast.show(response.message, '2000', 'center').subscribe(toast => {
        //   console.log(toast);
        // });
      }
      else {
        this.pswdForm.reset();
        this.myservice.show_alert('', response.message)
      }
    })
  }

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

  //for checking new pswd and confirm are same or not
  MatchPassword(val) {
    return new Promise(resolve => {
      if (val.value == this.pswdForm.value.new) {
        resolve(null);
      }
      else {
        resolve({ 'match': false });
      }
    })
  }

  //for checking current pswd and new pswd are same or not
  crnt_new_check(val) {
    return new Promise(resolve => {
      if (val.value == this.pswdForm.value.current) {
        resolve({ 'match': false });
      }
      else {
        resolve(null);
      }
    })
  }

}
