import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Events } from 'ionic-angular';
import { Validators, FormGroup, FormBuilder } from '@angular/forms'
import { Myservice } from '../../providers/myservice'
import { Storage } from '@ionic/storage';
import { Http } from '@angular/http'
import { OrderbyPipe } from '../../providers/sort-pipe';
import { user } from "../../models/mymodel";

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  loginForm: FormGroup
  codes:any;
  local:user

  constructor(public navCtrl: NavController, public navParams: NavParams, public events: Events, private formBuilder: FormBuilder, private myservice: Myservice, public storage: Storage, private http: Http, private orderbyPipe: OrderbyPipe) {

    this.loginForm = 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');
      })
  }

  open_page(page){
    this.navCtrl.push(page);
  }

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

  login(){
    this.myservice.show_loader()
    this.myservice.load_post(this.loginForm.value,'login').subscribe(response=>{
      if (response[0].status == 'success'){
        this.local = response[0].data
        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('user_data', response[0].data)
        var This = this;
        setTimeout(() => {
          This.myservice.hide_loader();
          This.events.publish('user:profile', response[0].data);
          This.navCtrl.setRoot('HomePage')
        }, 500);
      }
      else{
        this.myservice.hide_loader();
        this.myservice.show_alert('Failed', response[0].message)
      }
    })
  }

}
