import { Component, ViewChild } from '@angular/core';
import {GameService} from "../../providers/game-service";
import { NavParams, ViewController, ToastController, NavController, AlertController } from 'ionic-angular';
import { getScrollData } from '../../../node_modules/ionic-angular/umd/components/input/input';


@Component({
    templateUrl: './game-modal.html'
})

export class GameModalPage{

    @ViewChild('name') name;
    game: any = {};
    error: any;
    addGameCreds = {title: '', studio: '', platform:''};

    constructor(public gameService: GameService,
        public params: NavParams,
        public viewCtrl: ViewController,
        public toastCtrl: ToastController,
        public navCtrl: NavController,
        public alertCtrl: AlertController,
        ) {
        
            if (this.params.data.id) {
            this.gameService.getGame(this.params.get('id')).subscribe((game: any) => {
            this.game = game;
            this.game.href = game._links.self.href;});
            }
    }


dismiss(){
    this.viewCtrl.dismiss();
}

dismissAndAdd(){
    console.log("3. Before adding to user game ID: " + this.gameService.currentGameId);
    this.gameService.addGameToUser(this.gameService.currentGameId).subscribe( response => {
        console.log(response);
    });
    this.viewCtrl.dismiss();
}

addGame(){
    this.gameService.addGame(this.addGameCreds).subscribe(
        response=> {
            //stores the current game object and its id in gameservice
            this.gameService.currentGame = response;
            this.gameService.currentGameId = response.id;
            //toast to show it was created
            let toast = this.toastCtrl.create({
                message: 'Game Added',
                duration: 3000,
                position: 'bottom'
            });
            toast.present();
            //dismisses the modal page
            console.log("Before normal dismiss and add");
            this.dismissAndAdd();
        },
        error => {
            //this.showPopup("You have an error!", `Error code: ${error.status}`, [{text: "ok"}] )
            console.log("1. Found existing game ");
            this.getGameByName();
        }
    )
}

async getGameByName() {
    const response = await this.gameService.getGameByName(this.addGameCreds.title).toPromise();
    this.gameService.currentGameId = response;
    await this.dismissAndAdd();
    return response;
}

// getGameByName(){
//     this.gameService.getGameByName(this.addGameCreds.title).subscribe( response => {
//         this.gameService.currentGameId = response;
//         console.log("2. get game id by name: " + response);
//         this.dismissAndAdd();
//     };
// }

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


}