import { Component } from '@angular/core';
import { NavController, MenuController, LoadingController, ToastController } from 'ionic-angular';
import { TokenService } from '../../providers/token-service';
import { HallPage } from '../hall/hall';

@Component({
    selector: 'page-login',
    providers: [TokenService],
    templateUrl: 'login.html'
})
export class LoginPage {

    constructor(
        public navCtrl: NavController,
        public menuCtrl: MenuController,
        public tokenService: TokenService,
        public loaderCtrl: LoadingController,
        public toastCtrl: ToastController
    ) {}

    /**
     *
     */
    ionViewDidLoad() {
        this.menuCtrl.enable(false);

        if (this.tokenService.tokenIsPresent()) {
             this.goToHall();
        }
    }

    /**
     *
     */
    signin(): void {
        let loader = this.loaderCtrl.create({
             content: "Iniciando sesión, espere..."
        });

        loader.present();

        this.tokenService.getToken().then(r => {

            console.log(r);
            
            loader.dismiss();
            this.goToHall();
 
        }).catch(e => {
            console.log(e);
            loader.dismiss();
            
            this.toastCtrl.create({
                message: "No se pudo establecer una conexión al servidor",
                duration: 3000
            }).present();
        });
    }

    /**
     *
     */
    private goToHall(): void {
        this.navCtrl.setRoot(HallPage);
    }
}
