import { Component } from '@angular/core';
import { NavController, Loading, LoadingController, MenuController, ToastController } from 'ionic-angular';
import { ToolsProvider } from '../../providers/tools-provider';
import { LoginPage } from '../../pages/login/login';
import { HomePage } from '../../pages/home/home';

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

    loader: Loading;

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

    /**
     *
     */
    ionViewDidLoad() {
        this.loader = this.loaderCtrl.create({
            content: "Cargando aplicación, espere..."
        });
        
        this.loader.present();

        this.toolsProvider.initializeDatabase().then(r => { 
            this.loader.dismiss();
            this.goToHome();
        }).catch(e => {
            console.log(e);
            this.loader.dismiss();

            this.toastCtrl.create({
                message: "Petición de datos no válida",
                duration: 3000
            }).present();

            this.goToLogin();
        });
    }

    /**
     * Go to login
     */
    private goToLogin(): void {
        this.toolsProvider.clearPreferences();
        this.navCtrl.setRoot(LoginPage);
    }

    /**
     * Go to home
     */
    private goToHome(): void {
        this.navCtrl.setRoot(HomePage);
        this.menuCtrl.enable(true);
    }
}
