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";
@IonicPage()
@Component({
  selector: 'page-signin',
  templateUrl: 'signin.html',
})
export class SigninPage {
  codes: Array<dialcode>;
  signinForm: FormGroup

  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) {
    this.signinForm = this.formBuilder.group({
      mobile: ['', Validators.compose([Validators.required, this.myservice.checkLimit(10000000, 999999999999999)])],
      dial_code: ['+91', Validators.required],
      password: ['', Validators.compose([Validators.required, Validators.minLength(6)])]
    })

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

  login(){
    this.myservice.show_loader()
    this.myservice.load_post(this.signinForm.value,'driver_login').subscribe(response=>{
      if(response[0].status == 'success'){
        response[0].data.image = response[0].data.image.startsWith("http") ? response[0].data.image : this.myservice.base_url + response[0].data.image;
        this.storage.set('driver_data',response[0].data)
        var This = this;
        setTimeout(() => {
          This.myservice.hide_loader();
          This.events.publish('driver:profile', response[0].data);
          This.navCtrl.setRoot('HomePage')
        }, 500);
      }
      else{
        This.myservice.hide_loader();
        this.myservice.show_alert('', response.message)
      }
    })
  }

   forgot(){
  	this.navCtrl.push("ForgotPage");
  }

}
