import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams, Events } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
import { CommonProvider } from '../../providers/common/common';
import { Storage } from '@ionic/storage';

import {TranslateService} from '@ngx-translate/core';
import { SubjectService } from '../../providers/subject.service';
import { WebService_lang } from '../../providers/web.service';
import * as $ from 'jquery';
declare var google;

/**
 * Generated class for the ProfilePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

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

	@ViewChild('language') language: ElementRef;
	lang =  'en';

	result:any;
	profileForm: FormGroup;
	token:any;

  constructor(
		public translate: TranslateService,
    public subjectService: SubjectService,
    public service_lang: WebService_lang,
		public navCtrl: NavController,
		 public navParams: NavParams,
		 private camera: Camera,
		 public service: CommonProvider,
		 public storage: Storage,
		 private formBuilder: FormBuilder,
		public events: Events) {
  		this.profileForm = this.formBuilder.group({
	      firstname: ['', Validators.compose([Validators.required])],
	      lastname: ['', Validators.compose([Validators.required])],
	      phone_no: ['', Validators.compose([Validators.required, this.service.checkLimit(10000000, 999999999999999)])],
      	  email_id: ['', Validators.compose([Validators.required, Validators.pattern("[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}")])],
	      gender: ['Male'],
	    })
	  	this.service.show_loader(); 
	  	var This = this;
	  	this.storage.get('user_data').then(data => {
	        if(data){
	        	var timer = setInterval(function(){
	        		if(data.email_id!=''){
	        			clearInterval(timer);
	        			This.service.hide_loader();
	        			This.result = data;
				          This.profileForm.patchValue({
					    	firstname: This.result.firstname,
					    	lastname: This.result.lastname,
					    	phone_no: This.result.phone_no,
					    	email_id: This.result.email_id,
					    	gender:This.result.gender
					    });
	        		}
	        	},100)
	           
	          console.log(this.result);
	        }    
			})
			
			this.subjectService.getLangData().subscribe(langData => {
				console.log(langData);
				this.lang = this.service_lang.getLocalStorageItem('lang');
				console.log(this.lang);
				if (this.lang) {
					translate.setDefaultLang(this.lang);
					translate.use(this.lang);
				}
			});
	
			
			const lang  = this.service_lang.getLocalStorageItem('lang');
			console.log(lang);
	
			if(lang !== undefined){
				this.lang = lang;
			}
	
			if(this.lang === 'ru') {
				$('body').addClass('ru');
			} else {
				$('body').removeClass('ru');
			}
	
			//this.lang = 'en';
	
			translate.setDefaultLang(this.lang);
	
			// the lang to use, if the lang isn't available, it will use the current loader to get them
	
			translate.use(this.lang);


  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ProfilePage');

    
  }

  get_gender(type){
  	if(type==this.result.gender){
  		return true;
  	} else {
  		return false;
  	}
  }

  upload_img(sourceType:number){
		const options: CameraOptions = {
			quality: 100,
			destinationType: this.camera.DestinationType.FILE_URI,
			encodingType: this.camera.EncodingType.JPEG,
			mediaType: this.camera.MediaType.PICTURE,
			sourceType:sourceType
			//sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
		}

		this.camera.getPicture(options).then((imageData) => {
		// imageData is either a base64 encoded string or a file URI
		// If it's base64 (DATA_URL):
		//let base64Image = 'data:image/jpeg;base64,' + imageData;
		
		console.log(imageData);
		
		//if(imageData) {
			//this.load_post_file(imageData, {'auth_token':this.rider_data.auth_token , 'req_id' : this.data.req_id }, "delivery_photo_upload");
		//}else
			//this.myservice.show_alert("Error!", "Please upload an image to continue");
		
		}, (err) => {
		// Handle error
		});
	}

	profile_update(){
		var user_data = this.profileForm.value;
		this.storage.get('token').then(data => {
	        if(data){	          
	          var This = this;
	          this.service.show_loader(); 
	          var timer = setInterval(function(){
	            if(data!=''){
	              clearInterval(timer)
	              var post_data = {'token':data,'user_data':user_data};
	              This.service.post_data('updateuser',post_data).subscribe(response=>{
	                //This.result = data;
	                This.storage.set('user_data', response.profile);
        			This.events.publish('user:created', response.profile, Date.now());
	                This.service.presentToast("User Profile Update successfully");
	                This.service.hide_loader();
	                console.log(data);                         
	              })
	            } 
	          },100);
	        }    
    	})		
	}

}
