import { Component ,ElementRef, ViewChild} from '@angular/core';
import { IonicPage, NavController, NavParams ,Events,ModalController} from 'ionic-angular';
import {Validators, FormBuilder, FormGroup, FormControl, AbstractControl,FormArray } 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-addcar',
  templateUrl: 'addcar.html',
})
export class AddcarPage {
		@ViewChild("fileInput")  fileInput: ElementRef;
	services:any;
	location={'lat':'','lng':''};
	citie: any;
	coun: any;
	private editProform : FormGroup;
	address: any;
	user_data: any;
	componentForm: any;
	base64Image: any;
	garage_imgs: any = [];
	garageimgs: any= [];
	profile_pic: any;
	catagories: any;
	cat_vals: any =[];
	final_arr: any =[];

  constructor(public navCtrl: NavController, public navParams: NavParams, private eleRef:ElementRef,public storage:Storage, private myservice: Myservice, private formBuilder: FormBuilder,private transfer: FileTransfer, private file: File, private imagePicker: ImagePicker, public events: Events,public modalCtrl: ModalController) {
			this.editProform = this.formBuilder.group({ 
			name: ['',Validators.compose([Validators.maxLength(30), 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],
			mobile: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(20)])],
			description: ['', Validators.required],
			catagory: this.formBuilder.array([])
		});
		this.getServices()
		this.storage.get('user_data').then((user_data) => {
				console.log(user_data);
				if(user_data){
					this.user_data=user_data;
					this.get_profile();
				}else{
					let modal = this.modalCtrl.create('Loginbook');
		modal.onDidDismiss(data => {
			 console.log(data);
			if(data.user_data.id) {
				this.user_data = data.user_data;
				this.get_profile()
			}
		});
		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}
		console.log('on save',this.final_arr)
		const emailsFormArray = <FormArray>this.editProform.controls.catagory;
		 
			 var i
			for (i = 0; i < this.final_arr.length; i++) { 
				console.log('i',this.final_arr[i])
				emailsFormArray.push(new FormControl(this.final_arr[i]));
			}	
			
			var payload = {'img' :
				this.garage_imgs
			}
			var vl = JSON.stringify(payload)
		var obj = Object.assign(this.editProform.value, this.location,user_id,payload);
		this.fileChange()
		/* 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("success!", response.message);
				  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 
      	}
  }
  
 	fileChange() {
		     
		//let fileList: FileList = event.target.files;
		console.log('garage_imgs', this.garage_imgs)
		let fileList: FileList = this.garage_imgs
		if(fileList.length > 0) {
			 console.log('fileList', fileList)
			let file = fileList[0];      
			var ext = (file.name).split(".").pop();
			if(ext == 'jpg' ||ext == 'jpeg' || ext == 'png' ){ 
				var formData = new FormData();
				 
				 
				//arr =[{'data' : {'name':'olu', 'token' :'olus'}}];
				 var user_id ={'id':this.user_data.id}
				 var obj = Object.assign(this.editProform.value, this.location,user_id);
				//formData.append('name', names);
				formData.append('obj',obj);
				formData.append('uploadFile', file,file.name);
				
				 
				//this.medical_report = file.name;
				this.myservice.show_loader();
				this.myservice.fileUpload(formData, "editProfile").subscribe(response => {
				 
					this.myservice.hide_loader();
					if(response.status=='success'){
						this.myservice.show_alert('Success', response.message); 
					}
					else{
						this.myservice.show_alert('Error', response.message); 
						}
		 
		}) 
			} 
			else{ 
				this.myservice.show_alert('Error','Only JPEG, png or PDF is accepted'); 
			} 
		} 
	}
  
  	fileChanges(event,names) {
		     
		 
		     
		//let fileList: FileList = event.target.files;
		console.log('garage_imgs', event.target.files)
		let fileList: FileList = event.target.files;
		if(fileList.length > 0) {
			 console.log('fileList', fileList)
			let file = fileList[0];      
			 console.log('file', file)
			var ext = (file.name).split(".").pop();
			if(ext == 'jpg' ||ext == 'jpeg' || ext == 'png' ){ 
				var formData = new FormData();
				 
				 
				//arr =[{'data' : {'name':'olu', 'token' :'olus'}}];
				 var user_id ={'id':this.user_data.id}
				 var obj = Object.assign(this.editProform.value, this.location,user_id);
				//formData.append('name', names);
				formData.append('obj',obj);
				formData.append('uploadFile', file,file.name);
				
				 
				//this.medical_report = file.name;
				this.myservice.show_loader();
				this.myservice.fileUpload(formData, "editProfile").subscribe(response => {
				 
					this.myservice.hide_loader();
					if(response.status=='success'){
						this.myservice.show_alert('Success', response.message); 
					}
					else{
						this.myservice.show_alert('Error', response.message); 
						}
		 
		}) 
			} 
			else{ 
				this.myservice.show_alert('Error','Only JPEG, png or PDF is accepted'); 
			} 
		} 
	}
	
	openFolder(){ 
		let smallBox = this.eleRef.nativeElement.querySelector('.image_chooser'); smallBox.click();
	}
  
  
  
    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!", result.status);
			}
			else {
				
				this.myservice.show_alert("Success!", res.status);
				console.log("result", JSON.parse(result.response)  );
				
				console.log("pro pic", res.result.profile_pic);
				this.user_data.profile_pic = res.result.profile_pic;
					this.user_data.name = res.result.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};
		}
	}
	
	
	getServices(){ 
	
		this.myservice.show_loader();
		this.myservice.load_get("getServices").subscribe(response => {
			this.myservice.hide_loader();
			console.log(response);
			if(response.status == "success") {
				this.catagories = response.data;
				//this.myservice.show_alert("success!", response.message);
			}
			else {
		 
			}
		})  
	
  }
	
	get_cat(id){
		let index = this.cat_vals.findIndex(x => x == id)
		 
		if(index!=-1)
			return true;
	}
	 
	get_profile(){
		this.myservice.show_loader();
		this.myservice.load_get("get_profiles/id/"+this.user_data.id).subscribe(response => {
			this.myservice.hide_loader();
			if(response.status="success") {
				 
			this.cat_vals = response.result.category.split(",");
			this.final_arr = this.cat_vals
			 
			
	 console.log('pro',this.editProform.controls.catagory)
			
			 this.editProform.patchValue(response.result);
			 
			 this.location.lat = response.result.lat;
			 this.location.lng =response.result.lon;
				this.profile_pic = response.result.profile_pic
				/* 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) => { });
	}	
	
	uploadPictures(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.garage_imgs[pic]= results[0].toString();
					this.garageimgs[pic] = results[0];
				}
			
		}, (err) => { }); 
		console.log(this.garage_imgs);
	}
	
	
	private markFormGroupTouched(formGroup: FormGroup) {
		console.log(formGroup)
		if(formGroup.controls){
    	(<any>Object).values(formGroup.controls).forEach(control => {
      		control.markAsTouched();
      		if (control.controls) {
        		control.controls.forEach(c => this.markFormGroupTouched(c));
      		}
    	});
		}
  	}
	
	change_val(val,isChecked){
		console.log(val)
		console.log(this.cat_vals)
		
		
		let index = this.final_arr.findIndex(x => x == val.id)
		console.log(index)
		if(isChecked) {
			if(index==-1)
				this.final_arr.push(val.id);
			
			
		} else { 
		 this.final_arr.splice(index, 1);
			 
		}
		console.log(this.final_arr)
	}

}
