import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,Events, ModalController } from 'ionic-angular';
import {Validators, FormBuilder, FormGroup, FormControl, AbstractControl } from '@angular/forms';
import { Storage } from '@ionic/storage';
import {Myservice} from '../../providers/myservice';
declare var require: any;
declare var google: any;

@IonicPage()
@Component({
  selector: 'page-signup',
  templateUrl: 'signup.html',
})
export class SignupPage {
	services:any;
	location:any;
	citie: any;
	coun: any;
	signup: any;
		terms_service: any;
	address: any;
	componentForm: any;
  constructor(public navCtrl: NavController, public navParams: NavParams,public storage:Storage, private myservice: Myservice, private formBuilder: FormBuilder, public events: Events,public modalCtrl: ModalController) {
	this.getServices();
	this.get_terms()
		this.signup = this.formBuilder.group({ 
			email: ['', Validators.compose([Validators.pattern("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"), Validators.required])],
			password: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
			name: ['', Validators.compose([ Validators.pattern('^[A-Za-z]+( [A-Za-z]+)*$'), Validators.required])],
			city: ['',],
			postal_code: ['',Validators.compose([Validators.required, Validators.minLength(4), Validators.maxLength(4)])],
			address: ['', Validators.required],
			category: [''],
			cpassword: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
			mobile: ['', Validators.compose([Validators.required, Validators.minLength(8), Validators.maxLength(20)])],
			terms: [ 'false',Validators.requiredTrue],
		}, {
      validator: this.Match('password', 'cpassword')
    });
	
	this.componentForm = {
        locality: 'long_name'
       
    };
	 
  }
  

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

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

  otp()
  {
    this.navCtrl.push('OtpPag');
  }
  
  getServices(){ 
	
	this.myservice.show_loader();
	this.myservice.load_get("getServices").subscribe(response => {
		this.myservice.hide_loader();
		console.log(response);
		if(response.status == "success") {
			this.services = response.data;
			//this.myservice.show_alert("success!", response.message);
		}
		else {
	 
		}
	})  
	
  }
   
	signupForm(){
		if(this.signup.valid)
      	{
		this.myservice.show_loader();
		this.signup.controls['city'].setValue(this.citie);
		this.signup.controls['address'].setValue(this.address);
		var obj = Object.assign(this.signup.value, this.location);
		this.myservice.load_post(this.signup.value, "signup").subscribe(response => {
			this.myservice.hide_loader();
			console.log(response);
			if(response.status == "success") {
				  this.myservice.show_alert("success!", response.message);
				   this.navCtrl.setRoot('LoginPage');
			}
			else {
				
			  this.myservice.show_alert("Error!", response.message);
			  
			}
		})
		}
      	else{ // Form is not valid
      
        	this.markFormGroupTouched(this.signup); // function to mark fields as touched 
      	}
  }
  
  
  emailValidator(control: FormControl): {[s: string]: boolean} {
    if (!(control.value.toLowerCase().match('^[a-z0-9.]+( \ [_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)\\.(\.[a-z0-9-]{1,15})$'))) {
      return {invalidEmail: true};
    }
  }
     Match(firstControlName, secondControlName) {
    return (AC: AbstractControl) => {
      let firstControlValue = AC.get(firstControlName).value; // to get value in input tag
      let secondControlValue = AC.get(secondControlName).value; // to get value in input tag
      if (firstControlValue != secondControlValue) {
        AC.get(secondControlName).setErrors({mismatch: true});
        console.log(false);
      } else {
        console.log(true);
        return null
      }
    };
  }
  
  initialize() {
	console.log("initialize")
		var addressType='address_signup';
		var input = document.getElementById('address_signup');
		/* var options = {
			types: ['(cities)']
			
		}; */
		var autocomplete = new google.maps.places.Autocomplete(input);
		let thiss = this;
		google.maps.event.addListener(autocomplete, 'place_changed', function () {
		var place = autocomplete.getPlace();
		console.log(place.address_components);
		   for (var i = 0; i < place.address_components.length; i++) {
            addressType = place.address_components[i].types[0];
			 console.log(addressType);
          if (thiss.componentForm[addressType]) {
		   console.log(thiss.componentForm[addressType]);
            var val = place.address_components[i][thiss.componentForm[addressType]];
        // document.getElementById(addressType).value = val;
		  console.log(val);
      (document.getElementById(addressType) as HTMLInputElement).value= val;
	   
	  if(addressType=='locality'){ thiss.citie = place.address_components[i][thiss.componentForm['locality']]; }
	 
          }
        }
		thiss.address = place.formatted_address;
		 // thiss.signup.controls['address_signup'].setValue(place.formatted_address);
		var latLong = autocomplete.getPlace().geometry.location;
		var js=JSON.stringify(latLong);
		var par=JSON.parse(js);
		thiss.location = {lat : par.lat, lng : par.lng};
		/*
		thiss.address = place.formatted_address;
		console.log(placeA.formatted_address);
		var latLong = autocomplete.getPlace().geometry.location;
		var js=JSON.stringify(latLong);
		var par=JSON.parse(js);
		thiss.location = {lat : par.lat, lng : par.lng};
		  */
		//document.getElementById('driver_lat').value=par.lat;
		//document.getElementById('driver_lng').value=par.lng;
		// document.getElementById('pickup_lat').value=par.lat;
		// document.getElementById('pickup_lng').value=par.lng;
	});
		
	}

     	private markFormGroupTouched(formGroup: FormGroup) {
    	(<any>Object).values(formGroup.controls).forEach(control => {
      		control.markAsTouched();
      		if (control.controls) {
        		control.controls.forEach(c => this.markFormGroupTouched(c));
      		}
    	});
  	}
		get_terms(){
		//this.myservice.show_loader();
		this.myservice.load_get('get_terms').subscribe(data => {
			//this.myservice.hide_loader();
			if(data.status == 'success'){
				 
				console.log(data.result);
				this.terms_service = data.result
			}
		});
	}
	agree_terms(pg,evt){
		evt.stopPropagation();	
		let termsModal = this.modalCtrl.create('TermsPage',{'data' :this.terms_service,'page' : pg} );
		termsModal.present();
	}

}
