import { Component, ViewChild } from '@angular/core';
import { Nav, Platform, Events, AlertController } 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';
import { Network } from '@ionic-native/network';

@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, private network: Network, public alertCtrl: AlertController) {
    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();

      this.network.onDisconnect().subscribe(() => {

        const alert = this.alertCtrl.create({
          title: 'Network Error',
          message: 'No Internet Connection',
          buttons: [
            {
              text: 'Quit',
              handler: data => {
                this.platform.exitApp();
              }
            }, {
              text: 'Cancel',
              role: 'cancel'
            }
          ]
        });
        alert.present();

      });

    });
  }

  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 if (page == 'MytripsPage'){
      this.myservice.show_loader()
      this.nav.setRoot(page);
    }
    else
   this.nav.setRoot(page);
 }
}