import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,Events } from 'ionic-angular';
import {Validators, FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { Storage } from '@ionic/storage';
import {Myservice} from '../../providers/myservice';

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

	private LoginForm : FormGroup;
	 device_id:any;
	 lat_lng:any;
	
	constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, public storage: Storage, private myservice: Myservice, public events: Events) {
		this.storage.get('get_deviceId').then((deviceId) => {
				console.log(deviceId);
				if(deviceId){
					this.device_id = deviceId.userId
				}
			})
			this.storage.get('user_data').then((user_data) => {
				console.log(user_data);
				if(user_data){
					this.navCtrl.push('ListVehiclePage');
				}
			})
			this.storage.get('lat_lng').then((lat_lng) => {
			 
				if(lat_lng){
					this.lat_lng = lat_lng;
				}
			})
	
			this.LoginForm = this.formBuilder.group({ 
				email: ['', [Validators.required, this.emailValidator.bind(this)]],
				password: ['', Validators.required ] 
			});
			
			
			
			 
		/* this.LoginForm.controls['email'].valueChanges.subscribe(value => {
		  var mails= value.trim();
		  console.log(mails)
			this.LoginForm.controls['email'].patchValue(mails);
		});*/
	}
	
	trim_white(value){
		 var mails= value.trim();
		  console.log(mails);
		  this.LoginForm.controls['email'].patchValue(mails);
	}

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

	login() {
		this.navCtrl.push('HomePage');
	}

	signup(){
		this.navCtrl.push('SignupPage');
	}
	forgot_psw(){
		this.navCtrl.push('OtpPage');
	}
	OnLogin(){ 
		console.log(this.lat_lng)
		console.log(this.LoginForm.value)
		this.myservice.show_loader();
		var val = Object.assign({}, this.LoginForm.value , {'device_id' :this.device_id,'lat' : this.lat_lng.lat, 'lng' : this.lat_lng.lng})
		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);
							if(data.services > 0)
								this.navCtrl.setRoot('ListVehiclePage');
								 
							else
								this.navCtrl.setRoot('OfferedPage');
								 
					})
				});
			}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};
		}
	}

}
