import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Events } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup } from "@angular/forms";
import { Myservice } from "../../providers/myservice";
import { Http } from '@angular/http'
import { OrderbyPipe } from '../../providers/sort-pipe';
import { dialcode } from "../../models/mymodel";
import { Toast } from '@ionic-native/toast';
import { Storage } from '@ionic/storage';
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>;
  errors: string = '';

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

    this.signupForm = this.formBuilder.group({
      User_name: ['', Validators.compose([Validators.required, Validators.minLength(3)])],
      Mobile: ['', Validators.compose([Validators.required, this.myservice.checkLimit(10000000, 999999999999999)])],
      dial_code: ['+91', Validators.required],
      Email: ['', Validators.compose([Validators.required, Validators.pattern("[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}")])],
      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')])],
    })

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

  register() {
    this.myservice.show_loader()
    this.geolocation.getCurrentPosition().then((resp) => {
      
      this.myservice.load_post(this.signupForm.value, 'sign_up').subscribe(response => {
        if (response.status == 'success') {

          response.data.lat = resp.coords.latitude
          response.data.lng = resp.coords.longitude
          this.firebase.pushItem('users/', response.data)
          response.data.image = response.data.image.startsWith("http") ? response.data.image : this.myservice.base_url + response.data.image;
          this.myservice.hide_loader()
          this.storage.set('user_data', response.data);
          this.events.publish('user:profile', response.data);
          this.navCtrl.setRoot('HomePage')

          this.toast.show(response.message, '2000', 'center').subscribe(
            toast => {
              console.log(toast);
            });
        }
        else {
          this.myservice.hide_loader()
          for (let index = 0; index < response.error_list.length; index++) {
            this.errors = this.errors + response.error_list[index].message + '.<br/>'
          }
          this.myservice.show_alert('Failed', this.errors)
        }
      })
    }).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 });
      }
    })
  }
}
