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

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

  registerCredentials = {name: '', email: '', password:''};
  userId: number;

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

  public register() {
    this.authService.register(this.registerCredentials).subscribe(
      response => {
        //console.log(this.authService.currentUser.id);
        //get user ID and set
        this.authService.currentUser = response;
        this.authService.currentUserId = response.id;
        this.gameService.currentUserId = response.id;
       this.showPopup("You created account!", `Thank you for signing up ${response.name}!`,
         [{
            text: 'ok',
            handler: () => this.navCtrl.push(TabsPage)
         }]
       )
    },
      error => {
        this.showPopup("You have an error!", `Error code: ${error.status}`, [{ text: "ok"}])
      }
    ), () => {
      console.log("HIT")
      this.navCtrl.push(TabsPage)
    };
  }

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