import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
import { AuthServiceProvider } from '../../providers/auth-service';
import { GameService } from '../../providers/game-service';
import { TabsPage} from "../tabs/tabs";
import { RegisterPage } from '../register/register';


/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  loginCredentials = { email: '', password:''};

  constructor(public navCtrl: NavController, public navParams: NavParams,
              public authService: AuthServiceProvider,
              public alertCtrl: AlertController,
              public gameService: GameService) {
  }

  public login(){
    this.authService.login(this.loginCredentials.email).subscribe(
      response => {
        console.log(response);
        if (response == null){
           this.existingUser();
           return; 
        }
        this.authService.currentUser = response;
        this.authService.currentUserId = response.id;
        this.gameService.currentUserId = response.id;
        this.showPopup("Welcome back!", `Enjoy your stay ${response.name}!`,
         [{
            text: 'ok',
            handler: () => this.navCtrl.push(TabsPage)
         }]
       )
      },
      error => {
        this.showPopup("You have an error!", `Error code: ${error.status}`, [{ text: "ok"}])
      }

    )
  }

  existingUser(){
    this.showPopup("Try Registering!", `This user does not exist!`,
         [{
            text: 'ok',
            handler: () => this.navCtrl.push(RegisterPage)
         }]
       )
  }

  showPopup(title, text, buttons) {
    return this.alertCtrl.create({
      title: title,
      subTitle: text,
      buttons
    }).present();
  }

  createAccount(){
    this.navCtrl.push(RegisterPage);
  }

}
