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

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

  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, private translate: TranslateService, private storage: Storage, private menu:MenuController) {

    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');
      })
  }

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

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

  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.translate.get(['signup.' + response.message]).subscribe(value => {
            this.myservice.show_alert('', value['signup.' + response.message])
          })
        }
      })
    })
    }).catch((error) => {
      console.log('Error getting location', error);
    });
  }

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

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