import { Component, ViewChild } from '@angular/core';
import { Platform, Nav, AlertController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Storage } from '@ionic/storage';
import { VespotServiceProvider } from '../providers/vespot-service/vespot-service';
import { ShareService } from '../services/share/share';

import { HomePage } from '../pages/home/home';
import { DevicesPage } from '../pages/devices/devices';
import { Main } from '../pages/main/main';
import { ConfigurationPage } from '../pages/configuration/configuration';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
  //rootPage:any = HomePage;

  constructor(platform: Platform,
    statusBar: StatusBar,
    splashScreen: SplashScreen,
    private alertCtrl: AlertController,
  private storage: Storage,
  public vespotService: VespotServiceProvider,
  public shareService: ShareService) {
    /*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.
      statusBar.styleDefault();
      splashScreen.hide();
    });*/
    this.storage.get('remember').then((val)=>{
        if(val) {
          this.storage.get('authentication').then((valAuth)=>{
              this.authenticateUser(valAuth);
          });
        } else {
              this.nav.setRoot(HomePage);
        }
    });
  }

  authenticateUser(auth) {
    this.vespotService.getDevices(auth)
  	.subscribe(
        (data) => { // Success
          this.shareService.setDevices(data);
          this.shareService.setAuthToken(auth);
          this.nav.setRoot(Main);
        },
        (error) =>{
          this.nav.setRoot(HomePage);
        }
      );
  }

  openDevicesPage() {
    this.nav.push(DevicesPage);
  }

  openConfigurationPage() {
    this.nav.push(ConfigurationPage);
  }

  closeSession() {
    let alert = this.alertCtrl.create({
      title: 'Confirmación',
      message: 'Realmente desea cerrar Sesión?',
      buttons: [{
        text: 'Si',
        handler: () => {
          this.storage.set('authentication', '');
          this.storage.set('remember', false);
          this.storage.set('rootDevice', null);
          this.storage.set('startAlarm', false);
          this.storage.set('time', 30);
      	  this.nav.setRoot(HomePage);
        }
      },{
        text: 'No',
        handler: () => {
          alert.dismiss();
          return false;
        }
      }]
    });
    alert.present();
  }

}
