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';
import { PhotoViewer } from '@ionic-native/photo-viewer';
declare var require: any;
declare var google: any;

@IonicPage()
@Component({
  selector: 'page-addcar',
  templateUrl: 'addcar.html',
})
export class AddcarPage {
	services:any;
	location={'lat':'','lng':''};
	citie: any;
	coun: any;
	private editProform : FormGroup;
	address: any;
	user_data: any;
	componentForm: any;
	base64Image: any;
	profile_pic: any;	
	base64vehicle =[];
	vehicle_pic =[];

  constructor(public navCtrl: NavController, public navParams: NavParams,public storage:Storage, private myservice: Myservice, private formBuilder: FormBuilder,private transfer: FileTransfer, private file: File, private imagePicker: ImagePicker, public events: Events,public modalCtrl: ModalController,private photoViewer: PhotoViewer) {
			this.editProform = this.formBuilder.group({ 
			first_name:['', Validators.compose([Validators.maxLength(30), Validators.required])],
			last_name: ['', Validators.compose([Validators.maxLength(30), Validators.required])],
			car_model: ['', Validators.required],
			car_make: ['', Validators.required],
			city: ['',],
			postal_code: ['',Validators.compose([Validators.pattern("[0-9]*"), Validators.required,Validators.minLength(4),Validators.maxLength(4)])],
			address: ['', Validators.required],
			mobile:  ['',Validators.compose([Validators.pattern("[0-9]*"), Validators.required,Validators.minLength(10),Validators.maxLength(20)])],
		});
		console.log("addcar");
		this.storage.get('user_data').then((user_data) => {
				
				if(user_data){
					console.log(user_data);
					this.user_data=user_data;
					this.get_profile();
				}else{
					let modal = this.modalCtrl.create('Loginbook');
		modal.onDidDismiss(data => {
			 
			 if(data){
				 console.log("no");
			if(data.user_data.id) {
				this.user_data = data.user_data;
				this.get_profile()
			 }
				 }else{
					  console.log("ys");
					 this.navCtrl.setRoot('TabsPage');
				 }
		});
		modal.present();
		}
			})
	
	this.componentForm = {
        locality: 'long_name'
       
    };
  }

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

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

  servicehistory()
  {
    this.navCtrl.push('ServicehistoryPage');
  }
  
  Changepsw()
  {
    this.navCtrl.push('Changepsw');
  }
  
    edit_profile(){
		
		  if(this.editProform.valid)
      	{
		this.myservice.show_loader();
		this.editProform.controls['city'].setValue(this.citie);
		this.editProform.controls['address'].setValue(this.address);
		var user_id ={'id':this.user_data.id}
		var obj = Object.assign(this.editProform.value, this.location,user_id);
		 if(this.base64Image) {
			this.load_post_file(this.base64Image, obj, "editProfile");
		}else{
		this.myservice.load_post(obj, "editProfile").subscribe(response => {
			this.myservice.hide_loader();
			console.log(response);
			if(response.status == "success") {
				  this.myservice.show_alert("Changes are saved!", response.message);
				  
				 
					this.user_data.first_name = response.result.first_name;
					this.user_data.last_name = response.result.last_name;
					this.user_data.mobile = response.result.mobile;
					console.log(this.user_data);
					this.events.publish('user:update_profile', this.user_data);
				  this.get_profile();
			}
			else {
				
			  this.myservice.show_alert("Error!", response.message);
			  
			}
		})
		}
		}
      	else{ // Form is not valid
      
        	this.markFormGroupTouched(this.editProform); // function to mark fields as touched 
      	}
  }
 
      load_post_file(imageURI, post_data, fn_name) {
	  console.log(imageURI);
        let ft = this.transfer.create();
        let filename = imageURI.substr(imageURI.lastIndexOf('/')+1);
        let options = {
            fileKey: 'file',
            fileName: filename,
            mimeType: 'image/jpeg',
            chunkedMode: false,
            headers: {
                'Content-Type' : undefined
            },
            params: post_data
        }; 
        //ft.onProgress(this.onProgress);
		this.myservice.show_loader();
        ft.upload(imageURI, this.myservice.webservice_url+fn_name, options, false)
        .then((result: any) => {
            //this.success(result);
			this.myservice.hide_loader();
			console.log(result);
			  var res =JSON.parse(result.response);
				if(res.status == "failed") {
	  			this.myservice.show_alert("Error!", res.status);
			}
			else {
				
				this.myservice.show_alert("Success!", res.status);
				console.log("result", res  );
				console.log("resultval",res.result );
				
				console.log("pro pic", res.result.profile_pic);
				this.user_data.profile_pic = res.result.profile_pic;
					this.user_data.first_name = res.result.first_name;
					this.user_data.last_name = res.result.last_name;
					this.user_data.mobile = res.result.mobile;
					console.log(this.user_data);
					this.events.publish('user:update_profile', this.user_data);
					this.get_profile();
			}
        }).catch((error: any) => {
            //this.failed(error);
			console.log(error);
			//this.result = error;
			this.myservice.hide_loader();
			this.myservice.show_alert("Error!", 'Error occured. Please try again');
        });
		//console.log(this.result); 
		//return this.result;
  }
  
    initialize() {
	console.log("initialize")
		var addressType='address_editpro';
		var input = document.getElementById('address_editpro');
		/* 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_editpro'].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;
	});
		
	}
	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};
		}
	}
	nameValidator(control: FormControl): {[s: string]: boolean} {
		if ((control.value.toLowerCase().match(' /^[a-zA-Z]*$/'))) {
		return {invalid: true};
		}
	}
	
	 	get_profile(){
		this.myservice.show_loader();
		this.myservice.load_get("get_profile/id/"+this.user_data.id).subscribe(response => {
			this.myservice.hide_loader();
			if(response.status="success") {
			 
			 this.editProform.patchValue(response.result);
			 
			 this.location.lat = response.result.lat;
			 this.location.lng =response.result.lon;
				this.profile_pic = response.result.profile_pic
				this.vehicle_pic[1] = response.result.vehicle_pic1
				this.vehicle_pic[2] = response.result.vehicle_pic2
				/* if(response.length > 0){
					this.filter_hosp.controls['reasons'].setValue(response.reasons[0].id);
				} */
				
			}
			else { 
			  
			}
		})
}

	uploadPicture(){
	    var options ={	maximumImagesCount:1,
						width:400,
						height: 400,
						quality: 100
					}
		this.imagePicker.getPictures(options).then((results) => {
			for (var i = 0; i < results.length; i++) {
				console.log('Image URI: ' + results[i]);
				if(results[i]){
					this.base64Image = results[i];
					this.profile_pic = results[i];
				}
			}
		}, (err) => { });
	}
	
	uploadvehicleimg(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.base64vehicle[pic]= results[0];
					this.vehicle_pic[pic] = results[0];
				}
			
		}, (err) => { }); 
		console.log(this.base64vehicle);
	}
	
	 	private markFormGroupTouched(formGroup: FormGroup) {
    	(<any>Object).values(formGroup.controls).forEach(control => {
      		control.markAsTouched();
      		if (control.controls) {
        		control.controls.forEach(c => this.markFormGroupTouched(c));
      		}
    	});
  	}
	open_img(img)
  {
	this.photoViewer.show(img);
  }

}
