import { Component, ViewChild, ElementRef } from '@angular/core';
import { Nav, Platform, Events } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { LocationAccuracy } from '@ionic-native/location-accuracy';
import { Geolocation } from '@ionic-native/geolocation';
import { Storage } from '@ionic/storage';
import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder';
import { OneSignal } from '@ionic-native/onesignal';
import  { user } from '../providers/model/model';
import {TranslateService} from '@ngx-translate/core';
import { SubjectService } from '../providers/subject.service';
import { WebService_lang } from '../providers/web.service';
import * as $ from 'jquery';


@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
  @ViewChild('language') language: ElementRef;

  rootPage: any = "HomePage";
  device_id:any;
  local:user;
  lang =  'en';

  pages: Array<{title: string, component: any}>;

  constructor(public translate: TranslateService,
     public subjectService: SubjectService,
     public service_lang: WebService_lang, 
     public platform: Platform,
      public statusBar: StatusBar,
       public splashScreen: SplashScreen,
       public storage:Storage,
       /*private geolocation: Geolocation,
       private locationAccuracy: LocationAccuracy,
       private nativeGeocoder: NativeGeocoder, */
       public oneSignal: OneSignal,
        public events: Events) {

    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);

    // the lang to use, if the lang isn't available, it will use the current loader to get them
    events.subscribe('user:created', (user, time) => {
      console.log(user);
      this.local = user;
    });
    this.initializeApp();

    // used for an example of ngFor and navigation
/*    this.pages = [
      { title: 'Home', component: HomePage },
      { title: 'List', component: ListPage }
    ];*/

  }

  ngOnInit() {
    this.language.nativeElement.value = this.lang === 'ru' ? 1 : 0;
  }

  changeLang(val: string) {
    console.log("selected"+val);
    if (val == '1') {
      $('body').addClass('ru');
      this.lang = 'ru';
      this.service_lang.setLocalStorageItem('lang', 'ru');
      this.subjectService.changeLang('ru');
    } else {
      $('body').removeClass('ru');
      this.lang = 'en';
      this.service_lang.setLocalStorageItem('lang', 'en');
      this.subjectService.changeLang('en');
    }
    
  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.enable_location()
      this.storage.get('user_data').then(data => {
        console.log(data)
        if (data) {
          this.local = data
        }
      })
      this.triggerNotification();
    });
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page);
  }

  open_page(page){
   this.nav.push(page);
  }

  enable_location() {

    var current_loc = 'Infopark, Kakkanad, Ernakulam';
    var current_lat_lng = {'lat' : 10.0120 ,'lng' :76.3608}

    this.storage.set('current',{'location':current_loc,'lat_lng':current_lat_lng});
    this.storage.set('lat_lng', {'lat' : current_lat_lng.lat ,'lng' :current_lat_lng.lng} );

    /*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[]) => {
           /*This.storage.set('current_loc',result[0].subLocality+", "+result[0].locality+", "+result[0].subAdministrativeArea+", "+result[0].administrativeArea+", "+result[0].countryName);
            This.storage.set('current_lat_lng', {'lat' : data.coords.latitude ,'lng' :data.coords.longitude} );*/

            /*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});
            //This.openPage("HomePage");

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

         //"countryCode":"IN","countryName":"India","postalCode":"682030","administrativeArea":"Kerala","subAdministrativeArea":"Ernakulam","locality":"Kakkanad","subLocality":"Infopark"
       // data can be a set of coordinates, or an error (if an error occurred).
       // data.coords.latitude
       // data.coords.longitude
      });



    console.log("map called");
    let options = {
      enableHighAccuracy: true
    };
    this.locationAccuracy.canRequest().then((res: boolean) => {
      if (res) {
        console.log(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);
        let location_accuracyy = Number(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);
        let location_accuracy = location_accuracyy.toString();
        this.locationAccuracy.request(location_accuracyy).then((loc) => {
          this.geolocation.getCurrentPosition().then(pos => {
            console.log('lat: ' + pos.coords.latitude + ', lon: ' + pos.coords.longitude);
            console.log(pos);
            this.storage.set('lat_lng', {'lat' : pos.coords.latitude ,'lng' :pos.coords.longitude} );
             
    
          }).catch((err) => {
             alert(err);
          })
        }, (error) => {
              alert(error); 
          })
      }
    },(error)=>{
      console.log(error);
    })*/
  }

  triggerNotification() {
    var This = this;
    this.oneSignal.startInit('cd0f950d-2b1c-4c16-949d-bff73a8c1f56', '255038393105');

    this.oneSignal.registerForPushNotifications();

    this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.None);

    this.oneSignal.getIds().then((ids) => {
      console.log('getIds: ' + JSON.stringify(ids));
      this.device_id =ids;
      console.log(this.device_id.userId);
      This.storage.set('get_deviceId',this.device_id);
    });

    console.log('here i');

    this.storage.get('get_deviceId').then(data => {
      console.log("asdasdasdsad");
      console.log(data);
      if(data){
        this.device_id = data.userId;
        console.log(this.device_id.userId);
      }
    })

    this.oneSignal.handleNotificationReceived().subscribe((msg) => {
      console.log('Notification received');
      console.dir(msg);
    }); 

    this.oneSignal.handleNotificationOpened().subscribe((msg) => {
      console.log('Notification opened');
       this.nav.push('HomePage');
     /*console.log(JSON.stringify(msg));
      var pool_id = msg.notification.payload.additionalData.pool_id;
      if(pool_id)
        this.nav.setRoot('QuoteDetailsPage',{'pool_id' : pool_id,'from_push' : false});*/
     //console.log(this.event_id);
     //this.detail(this.event_id);
    });
     this.oneSignal.endInit();
   }

   login(){
    this.storage.remove('user_data');
    this.storage.remove('token');
    this.local = undefined;
    this.nav.setRoot("LoginPage");
   }


   
 
}
