import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams,ModalController,AlertController  } from 'ionic-angular';
import { CommonProvider } from '../../providers/common/common';
import { Storage } from '@ionic/storage';
import { Geolocation } from '@ionic-native/geolocation';
import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder';
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;

@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})
export class HomePage {
  @ViewChild('language') language: ElementRef;
  lang =  'en';
	user_id:any;
	result:any;
  filters:any;
  myInput:any;
  componentForm:any;
  place_choose:boolean = true;
  selected_location:any;
  location:number = 1;
  selected_lat_lng:any;
  constructor(
    public translate: TranslateService,
    public subjectService: SubjectService,
    public service_lang: WebService_lang, 
		public navCtrl: NavController, 
  	public navParams: NavParams,
  	public service: CommonProvider,
  	public modalCtrl: ModalController,
  	public storage: Storage,
    private geolocation: Geolocation,
    private nativeGeocoder: NativeGeocoder,
    private alertCtrl: AlertController
  	) {
    this.componentForm = {
      locality: 'long_name',
    };
    this.place_choose = true;
    this.location = 1;
    this.storage.get('set_location').then(data=>{
      if(data){
        this.selected_location = data.location;
      } else {
        this.storage.get('current').then(curr_data=>{
          if(curr_data){
            this.storage.set('set_location',{'location':curr_data.location,'lat_lng':curr_data.lat_lng})
            this.selected_location = curr_data.location;
            this.selected_lat_lng = curr_data.lat_lng;
          } else {
            this.enable_location();            
          }
          
        })
      }      
    })


    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() {
    this.filters = {"service":[],"offer":"","gender":"","location":"","key_word":""};
    var This = this;
    this.service.show_loader();
     var timer = setInterval(function(){
     This.storage.get('set_location').then(data=>{
       if(data!=undefined){
         console.log("enter");
         console.log(data);
         clearInterval(timer);
         This.service.hide_loader();
         //This.get_current();
         This.view_shop_list();
       } else {    
       console.log("loop");     
         //This.service.show_loader();
         This.enable_location();
         This.storage.get('current').then(curr_data=>{
          if(curr_data){
            This.storage.set('set_location',{'location':curr_data.location,'lat_lng':curr_data.lat_lng})
            clearInterval(timer);
            This.selected_location = curr_data.location;
            This.selected_lat_lng = curr_data.lat_lng;
            This.get_current();
          }          
        })
       }
     })
    },1000);

    

    console.log('ionViewDidLoad HomePage');

  }

  


  view_shop_list(){

    this.service.show_loader(); 
    var This = this;
    console.log("shop list called");
    
    this.storage.get('token').then(data => {
      if(data){
        post_data['token'] = data;
      }    
    })
    var post_data = {"current_lat":"","current_lng":"","page":"1","filter":this.filters}
    this.storage.get('set_location').then(data=>{
      console.log("set location");
      console.log(data)
      if(data){
          post_data.current_lat = data.lat_lng.lat;
          post_data.current_lng = data.lat_lng.lng;
          console.log(post_data)
          this.onInput('');
          /*setTimeout(function(){
          This.service.post_data('shop_list',post_data).subscribe(data=>{
            This.result = data;
            This.service.hide_loader();
            //console.log(data);
          })
        },500);*/
        This.service.hide_loader();
      } else {
        this.service.presentToast("Something error found in location access. Please reset your location");
        var This = this;
        setTimeout(function(){
          This.service.hide_loader();
          This.presentConfirm();
        },5000);
        //this.get_current();
        //this.enable_location();  

      }
    })
  }

  presentConfirm() {
  let alert = this.alertCtrl.create({
    title: 'Enable Location',
    message: 'Please allow your location',
    buttons: [      
      {
        text: 'Allow',
        handler: () => {
          window.location.reload();
        }
      }
    ]
  });
  alert.present();
}



  get_current(){
    this.location = 1;
    var This = this;
    this.storage.get('current').then(data=>{
      if(data){
        console.log(data);
        console.log("get current location")
        this.selected_location = data.location;
        this.selected_lat_lng = data.lat_lng
        this.storage.set('set_location',{'location':data.location,'lat_lng':data.lat_lng})
        setTimeout(function(){   
          This.map_fu();
          This.myInput = '';
          This.onInput('');
        },500);
      }      
    })
    //this.place_choose = true;
  }

  get_elipse(des:string){
  	var args = 100;
  	if (des.length > args) {
      return des.substring(0, args) + '...';
    } else {
      return des;
    }
  }

  doInfinite(infiniteScroll){
  	console.log('Begin async operation');
  	var This = this;
  	var post_data = {"current_lat":"","current_lng":"","page":"1","filter":this.filters}
    this.storage.get('set_location').then(data=>{
          post_data.current_lat = data.lat_lng.lat;
          post_data.current_lng = data.lat_lng.lng;
    })

    this.storage.get('token').then(data => {
      if(data){
        post_data['token'] = data;
      }    
    })
    setTimeout(() => {
      /*for (let i = 0; i < 30; i++) {
        this.items.push( this.items.length );
      }

      console.log('Async operation has ended');*/
      if(This.result.shop_count>This.result.shops.length){
        setTimeout(function(){
        	This.service.post_data('shop_list',post_data).subscribe(data=>{
    	  		data.shops.forEach(function(item){
    	  			This.result.shops.push(item);
    	  		})
    	    })
        },500);
      }


      infiniteScroll.complete();
    }, 500);
  }

  round2Fixed(value) {
	  value = +value;

	  if (isNaN(value))
	    return NaN;

	  // Shift
	  value = value.toString().split('e');
	  value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + 2) : 2)));

	  // Shift back
	  value = value.toString().split('e');
	  return (+(value[0] + 'e' + (value[1] ? (+value[1] - 2) : -2))).toFixed(2);
	}

	view_shop(id){
		this.navCtrl.push('DetailedPage',{'shop_id':id});
	}


	filter(){
    this.map_fu();
		let filterModal = this.modalCtrl.create("FilterPage",{"params":this.result.services});
		filterModal.onDidDismiss(data => {
      console.log(data);
      var This = this;
      if(data!=undefined){
      var post_data = {"current_lat":"","current_lng":"","page":"1","filter":""}
      this.storage.get('set_location').then(curr_data=>{
        if(curr_data){
          post_data.current_lat = curr_data.lat_lng.lat;
          post_data.current_lng = curr_data.lat_lng.lng;
          this.selected_location = curr_data.location;
        }          
      })




      post_data.filter = data;

      if(this.myInput!=''){
        post_data.filter['key_word'] = this.myInput;
      }

      if(data.location!=''){
        post_data.current_lat = data.location.lat;
        post_data.current_lng = data.location.lng;
      }
      this.storage.get('token').then(data => {
        if(data){
          post_data['token'] = data;
        }    
      })
      //console.log(data);
      this.service.show_loader(); 
      setTimeout(function(){
        This.service.post_data('shop_list',post_data).subscribe(data=>{
          This.result = data;
          This.service.hide_loader();
          //console.log(data);
        })
      },500);


      }


		})
		filterModal.present();

	}

  onInput(keyword){    
    console.log(keyword);
    console.log(this.filters);
    //this.myInput = keyword.data;
    var post_data = {"current_lat":"","current_lng":"","page":"1","filter":this.filters}
    this.storage.get('set_location').then(curr_data=>{
      if(curr_data){
        post_data.current_lat = curr_data.lat_lng.lat;
        post_data.current_lng = curr_data.lat_lng.lng;
        console.log(curr_data);
      }
          
    })
    
    this.storage.get('token').then(data => {
        if(data){
          post_data['token'] = data;
        }    
      })
      post_data.filter['key_word'] = '';
      if(this.myInput!=''){
        post_data.filter['key_word'] = keyword;
      } 
      var This = this;
      this.service.show_loader(); 
      setTimeout(function(){
        console.log('Post data to send',post_data);
        This.service.post_data('shop_list',post_data).subscribe(data=>{
          This.result = data;
          This.service.hide_loader();
          //console.log(data);
        })
      },500)

      
  }

  edit_place(){
    console.log("called Place")
    this.place_choose = !this.place_choose;
  }

  initialize(evt) {
    console.log('map', evt)
    var elm = evt.target.id;
    var addressType=elm;
    var input = document.getElementById(elm);
    var options = {
      //types: ['(cities)']      
    };
    this.location = 0;
    var autocomplete = new google.maps.places.Autocomplete(input,options);      
    var thiss = this;
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
      thiss.map_fu();
      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(addressType =='locality'){
          var val = place.address_components[i][thiss.componentForm[addressType]];          
          (document.getElementById(elm) as HTMLInputElement).value= place.formatted_address;
        }
        console.log(val);
      }      
      console.log(place.formatted_address)
      thiss.selected_location = place.formatted_address;
      var latLong = autocomplete.getPlace().geometry.location;
      var js=JSON.stringify(latLong);
      var par=JSON.parse(js);

      var sel_location = place.formatted_address;
      var lat_lng = {"lat":par.lat,"lng":par.lng};
      thiss.selected_lat_lng = lat_lng;
      thiss.storage.set('set_location',{'location':sel_location,'lat_lng':lat_lng});
           console.log('Test');
      setTimeout(function(){ 
      console.log('inside settimeout function')  
        thiss.map_fu();
        thiss.myInput = '';
        thiss.onInput('');
      },500);

      console.log(thiss.location);
    });    
  }

  map_fu(){
    console.log("function called");
    this.place_choose = true;
  }

  enable_location() {

    let optionss: NativeGeocoderOptions = {
        useLocale: true,
        maxResults: 5
    };

    this.geolocation.getCurrentPosition().then((resp) => {
       //console.log(resp);
       //console.log(resp);
       this.nativeGeocoder.reverseGeocode(resp.coords.latitude, resp.coords.longitude, optionss).then((result: NativeGeocoderReverseResult[]) => console.log(JSON.stringify(result[0]))).catch((error: any) => console.log(error));
      }).catch((error) => {
        console.log('Error getting location', error);
      });

      let watch = this.geolocation.watchPosition();
      var This = this;
      watch.subscribe((data) => {
        console.log(data);
         this.nativeGeocoder.reverseGeocode(data.coords.latitude, data.coords.longitude, optionss).then((result: NativeGeocoderReverseResult[]) => {
            var current_loc = result[0].subLocality+", "+result[0].locality+", "+result[0].subAdministrativeArea+", "+result[0].administrativeArea+", "+result[0].countryName;
            var current_lat_lng = {'lat' : data.coords.latitude ,'lng' :data.coords.longitude};

            This.storage.set('current',{'location':current_loc,'lat_lng':current_lat_lng});
            //window.location.reload();

           console.log(JSON.stringify(result[0]))
         }).catch((error: any) => console.log(error));
      });    
  }

  

}
