import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,Events , ViewController} 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-loginbook',
  templateUrl: 'loginbook.html',
})
export class Loginbook {

	private LoginForm : FormGroup;
	device_id:any;
	services:any;
	location:any;
	citie: any;
	coun: any;
	signup: any;
	address: any;
	componentForm: any;
	login_clicked :any = true;
	signup_clicked :any = false;
	constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, public storage: Storage, private myservice: Myservice, public events: Events,public viewCtrl: ViewController) {
	 this.storage.get('get_deviceId').then((deviceId) => {
				console.log(deviceId);
				if(deviceId){
					this.device_id = deviceId.userId
				}
			})		

		this.LoginForm = this.formBuilder.group({ 
				email: ['', [Validators.required, this.emailValidator.bind(this)]],
				password: ['', Validators.required ] 
			});
			
		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)])],
			first_name:  ['', Validators.compose([Validators.maxLength(30), Validators.required])],
			last_name: ['', Validators.compose([Validators.maxLength(30), Validators.required])],
			city: ['',],
			postal_code: ['',Validators.compose([Validators.required, Validators.minLength(4), Validators.maxLength(4)])],
			address: ['', Validators.required],
			cpassword: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
			mobile: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(20)])],
		}, {
      validator: this.Match('password', 'cpassword')
    });
	
	this.componentForm = {
        locality: 'long_name'
       
    };
			
	}

	ionViewDidLoad() {
		console.log('ionViewDidLoad Loginbook');
	}
	
	trim_white(value){
		 var mails= value.trim();
		  console.log(mails);
		  this.LoginForm.controls['email'].patchValue(mails);
	}
		
	login() {
		this.navCtrl.setRoot('HomePage');
	}
	forgot_psw(){
		this.navCtrl.setRoot('OtpPage',{'page':'loginbook'});
	}

	signup_button(){
		this.login_clicked = false;
		this.signup_clicked = true;
		//this.navCtrl.push('SignupPage',{'page':'loginbook'});
	}
	skip(){
		this.navCtrl.setRoot('TabsPage');
	}
	OnLogin(){ 
		console.log(this.LoginForm.value)
		this.myservice.show_loader();
		var val = Object.assign({}, this.LoginForm.value , {'device_id' :this.device_id})
		this.myservice.load_post(val,'login').subscribe(data =>{
			console.log(data);
			this.myservice.hide_loader();
			if(data.status=='success'){
			
				this.storage.set('user_data',data.data).then(()=>{
					this.myservice.hide_loader();
					this.storage.get('user_data').then((user_data) => {
							this.events.publish('user:update_profile', user_data);
							this.viewCtrl.dismiss({'user_data':user_data }); 
								 
							 
					})
				});
			}else
				this.myservice.show_alert("Error!", data.message);
		});
	}
	
	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};
		}
	}
	
	close_login(){
		this.viewCtrl.dismiss();
	}
	
	
	
	  signupForm(){
	  if(this.signup.valid)
      	{
		this.myservice.show_loader();
		this.signup.controls['city'].setValue(this.citie);
		this.signup.controls['address'].setValue(this.address);
		var val = Object.assign({}, this.signup.value , {'device_id' :this.device_id})
		var obj = Object.assign(val, 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.push('LoginPage');
				  this.storage.set('user_data',response.data).then(()=>{
					this.myservice.hide_loader();
					this.storage.get('user_data').then((user_data) => {
							this.events.publish('user:update_profile', user_data);
							
								 this.viewCtrl.dismiss({'user_data':user_data }); 
							
							 
							 
					})
				});
			}
			else {
				
			  this.myservice.show_alert("Error!", response.message);
			  
			}
		})
			}
      	else{ // Form is not valid
      
        	this.markFormGroupTouched(this.signup); // function to mark fields as touched 
      	}
  }
  
  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));
      		}
    	});
  	}

}
