import { Component } from '@angular/core';
import { NavController, MenuController, LoadingController, Loading, AlertController, NavParams } from 'ionic-angular';
import { Validators, FormGroup, FormBuilder } from "@angular/forms";

import { AuthService } from "../../services/auth-service";
import { PouchService } from "../../services/pouch-service";

import { Credential } from "../../models/credential";

import { HomePage } from "../home/home";

@Component({
  	selector: 'page-login',
  	templateUrl: 'login.html'
})
export class LoginPage {
	
	loader: Loading;
	loginForm: FormGroup;

	constructor(
		public navCtrl: NavController,
		public menuCtrl: MenuController,
		public loadingCtrl: LoadingController,
		public alertCtrl: AlertController,
		public navParams: NavParams,
		public formBuilder: FormBuilder,
		public auth: AuthService,
		public pouch: PouchService
	) { 
		this.loginForm = this.formBuilder.group({
			host: ['http://localhost:8100', Validators.required],
			database: ['odoo', Validators.required],
			username: ['admin', Validators.required],
			password: ['admin', Validators.required],
		});
	}

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

		this.auth.skipSignin().subscribe(result => { 
			if (result.count > 0) {
				this.navCtrl.setRoot(HomePage);
			}
		}, error => console.log(error));
	}
	
	/**
	 *
	 */
	signin(loginInformation): void {
		this.loader = this.loadingCtrl.create({
			content: "Identificando usuario, espere..."
		});
		this.loader.present();
		this.auth.signin(loginInformation).subscribe(result => this.signinSuccess(result), error => this.signinError(error));
	}

	/**
	 *
	 */
	signinSuccess(data: any): void {
		this.loader.dismiss();
		console.log(data);
	}

	/**
	 *
	 */
	signinError(error: any): void {
		console.log(error);
		
		this.loader.dismiss();
		this.alertCtrl.create({
			title: 'Atención',
			message: 'No se puede conectar al servidor',
			buttons: [
				'Aceptar'
			]
		}).present();
	} 
}
