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

@IonicPage()
@Component({
  selector: 'page-signin',
  templateUrl: 'signin.html',
})
export class SigninPage {
  codes: Array<dialcode>;
  signinForm: FormGroup
  lang: string = 'en';

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

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

  ionViewDidEnter() {
    this.menu.swipeEnable(false);
    this.langTrans()
  }

  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);
          if (This.navParams.get('id')) {
            this.navCtrl.setRoot('HomePage', { id: This.navParams.get('id'), from: This.navParams.get('from') })
          }
          else
            This.navCtrl.setRoot('HomePage')
        }, 500);
      }
      else {
        this.myservice.hide_loader();
        this.translate.get(['signin.' + response[0].message]).subscribe(value => {
          this.myservice.show_alert('', value['signin.' + response[0].message])
        })
      }
    })
  }

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

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

}
