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';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { ImagePicker } from '@ionic-native/image-picker';

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;
	successs: any;
	address: any;
	componentForm: any;
	device_id:any;
	image_needed:boolean=false;
	base64Image= [];
	profile_pic= [];
	
  constructor(public navCtrl: NavController, public navParams: NavParams,public storage:Storage, private myservice: Myservice, private formBuilder: FormBuilder, public events: Events,public modalCtrl: ModalController,private transfer: FileTransfer, private file: File,private imagePicker: ImagePicker) {
		this.get_terms()
	 this.storage.get('get_deviceId').then((deviceId) => {
				console.log(deviceId);
				if(deviceId){
					this.device_id = deviceId.userId
				}
			})
			
			
		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(8), Validators.maxLength(20)])],
			car_model: ['', Validators.required],
			car_make: ['', Validators.required],
			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');
	}
  
	signupForm(){
		if(this.signup.valid)
		{
			console.log(this.base64Image.length);
			if(this.base64Image.length <1){
				this.image_needed =false;
				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.load_post_multifile(this.base64Image, this.signup.value, "signup");
				/*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.navCtrl.setRoot('TabsPage');
									 
							})
						});
					}
					else {
						this.image_needed =true;
					}
				}) */
			}else
				this.image_needed =true;
		}else{ // Form is not valid
			this.markFormGroupTouched(this.signup); // function to mark fields as touched 
		}
	}
	
	load_post_multifile(imageURI, post_data, fn_name) {
		
		this.myservice.show_loader();
		var i;
		for (i = 1; i < imageURI.length; i++) {
			if(imageURI[i]!=undefined){
				console.log("imageURI" ,imageURI[i]);
				let ft = this.transfer.create();
				let filename = imageURI[i].substr(imageURI[i].lastIndexOf('/')+1);
				let options = {
					fileKey: 'file',
					fileName: filename,
					mimeType: 'image/jpeg',
					chunkedMode: false,
					headers: {
						'Content-Type' : undefined
					},
					params: post_data
				};  
				ft.upload(imageURI[i], this.myservice.webservice_url+fn_name, options, false)
				.then((result: any) => {
					this.myservice.hide_loader();
					console.log('result ' + i, result);
					this.successs=true;
					console.log('imageURIlength ',imageURI.length);
					console.log('i ',i);
					this.storage.set('user_data',result.data).then(()=>{
						this.storage.get('user_data').then((user_data) => {
							this.events.publish('user:update_profile', user_data);
							this.navCtrl.setRoot('TabsPage');
									 
						})
					});
				}).catch((error: any) => {
					this.myservice.hide_loader();
					this.successs=false;
					this.myservice.show_alert("Error!", 'No garages found');
				});
			}
		}
		console.log(this.successs);
		//if(i == imageURI.length)
			//this.navCtrl.push('SuccessPage',{'page':'car_details'});
		 
	}
  
	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));
      		}
    	});
  	}
	
	agree_terms(pg){
		
		let termsModal = this.modalCtrl.create('TermsPage',{'data' :this.terms_service,'page' : pg} );
		termsModal.present();
	}
	
	uploadPicture(pic){
	   console.log(pic);
	   var options ={	maximumImagesCount:1,
						width:400,
						height: 400,
						quality: 100
					}
		this.imagePicker.getPictures(options).then((results) => {
		 console.log(results.length);
		 console.log(results[0]);
			 
				if(results){
					this.base64Image[pic]= results[0];
					this.profile_pic[pic] = results[0];
				}
			
		}, (err) => { }); 
		console.log(this.base64Image);
	}
	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
			}
		});
	}

}
