import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } 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 { OneSignal } from "@ionic-native/onesignal";
import { fireService } from "../../providers/firebase.service";
import { Geolocation } from '@ionic-native/geolocation';

@IonicPage()
@Component({
  selector: 'page-signup',
  templateUrl: 'signup.html',
})
export class SignupPage {
  signupForm: FormGroup
  codes: Array<dialcode>;

  constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, private http: Http, private orderbyPipe: OrderbyPipe, private myservice: Myservice, private onesignal: OneSignal, private firebase: fireService, private geolocation: Geolocation) {

    this.signupForm = 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: ['+91', Validators.required],
      password: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
      confirm: ['', Validators.compose([Validators.required]), this.MatchPassword.bind(this)],
      terms: [null, Validators.compose([Validators.required, Validators.pattern('true')])],
      phone: ['', Validators.compose([Validators.required, this.myservice.checkLimit(10000000, 999999999999999)])],
      deviceid: ['']
    })

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

  ionViewDidLoad() {
    console.log('ionViewDidLoad SignupPage');
  }

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

  register() {
    this.myservice.show_loader()
    this.geolocation.getCurrentPosition().then((resp) => {

    // this.onesignal.getIds().then((id) => {
      this.signupForm.controls['deviceid'].setValue(0/*id.userId*/)

      this.myservice.load_post(this.signupForm.value, 'driver_sign_up').subscribe(response => {
        this.myservice.hide_loader()
        if (response.status == 'success') {
          response.data.lat = resp.coords.latitude
          response.data.lng = resp.coords.longitude
          response.data.started = false
          response.data.status = 'offline'
          this.firebase.pushItem('drivers/', response.data)
          this.navCtrl.setRoot("SigninPage");
        }
        else {
          this.myservice.show_alert('', response.message)
        }
      })
    // })
    }).catch((error) => {
      console.log('Error getting location', error);
    });
  }

  MatchPassword(val) {
    return new Promise(resolve => {
      if (val.value == this.signupForm.value.password) {
        resolve(null);
      }
      else {
        resolve({ 'match': false });
      }
    })
  }
}
