import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { Main } from '../main/main'
import { AlertController } from 'ionic-angular';
import { VespotServiceProvider } from '../../providers/vespot-service/vespot-service';
import { ShareService } from '../../services/share/share';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  user:any;
  password:any;
  remember:any;

  constructor(public navCtrl: NavController,
		public alertCtrl: AlertController,
		public vespotService: VespotServiceProvider,
    public shareService: ShareService,
    private storage: Storage) {
      this.storage.get('remember').then((val)=>{
          if(val) {
            this.storage.get('authentication').then((valAuth)=>{
                this.authenticateUser(valAuth);
            });
          }
      });
  }

  /*ionViewCanEnter() {
  }*/

  authenticateUser(auth) {
    this.vespotService.getDevices(auth)
  	.subscribe(
        (data) => { // Success
          this.shareService.setDevices(data);
          this.shareService.setAuthToken(auth);
          if(this.remember == true) {
            this.storage.set('remember', true);
            this.storage.set('authentication', auth);
            this.storage.set('startAlarm', true);
            this.storage.set('time', 30);
          }

          this.navCtrl.setRoot(Main);
        },
        (error) =>{
          let alert = this.alertCtrl.create({
        title: 'Advertencia',
        subTitle: 'Usuario y Contraseña Incorrectos',
        buttons: ['OK']
      });
      alert.present();
        }
      );
  }

  login() {
    let auth = btoa(this.user + ':' + this.password);
    this.authenticateUser(auth);
  }

}
