import { Component, ViewChild } 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 { Storage } from '@ionic/storage';
import { user } from '../models/mymodel'
import { Myservice } from "../providers/myservice";
import { LocationAccuracy } from '@ionic-native/location-accuracy';

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

  rootPage: string ;
  local:user;

  constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, public storage: Storage, public events: Events, private myservice: Myservice, private locationAccuracy: LocationAccuracy) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {

      this.storage.get('user_data').then(data=>{
        console.log(data)
        if(data){
          this.rootPage = 'HomePage'
          this.local = data
          console.log(this.local)
        }
        else
          this.rootPage = 'LandingPage'
      })

      this.events.subscribe('user:profile', data => {
        this.local = data
        if (this.local) {
          this.local.image = this.local.image.startsWith("http") ? this.local.image : this.myservice.base_url + this.local.image;
          console.log(this.local)
        }
      })

    this.statusBar.styleDefault();
    this.splashScreen.hide();
      // this.enableLoc();

    });
  }

  enableLoc(){
    this.locationAccuracy.canRequest().then((canRequest: boolean) => {

      if (canRequest) {
        // the accuracy option will be ignored by iOS
        this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
          () => console.log('Request successful'),
          error => console.log('Error requesting location permissions', error)
        );
      }

    });
  }

  open_page(page){
    if (page =='LandingPage'){
      this.storage.remove('user_data');
      this.nav.setRoot(page);
      this.events.publish('user:profile', '');
    }
    else
   this.nav.setRoot(page);
 }
}