import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AlertService } from '../services/alert.service';
import { GameService } from '../services/game.service';

@Component({
  selector: 'app-home',
  templateUrl: 'valuesAlign.page.html',
  styleUrls: ['valuesAlign.page.scss'],
})
export class ValuesAlignPage {

  mayContinue: boolean;
  nextGame: string;

  constructor(private router: Router, private game: GameService, public alert: AlertService) {}

  async checkValues(){

    // check if all cards have a value
    for(const card of this.game.cardset){
      if(card.value == 0){
        return false;
      }
    }
    return true;
  }

  async userClickedButton(card, value) {
    // card.value 0 = nothing chosen, 1 = hearts, 2 = cross
    // get card index from array and change the value
    const cardIndex = this.game.cardset.findIndex((obj => obj.id == card.id));
    this.game.cardset[cardIndex].value = value;
    // check if all cards have a value
    if(!(await this.checkValues())){
      return;
    }

    // User may continue
    this.mayContinue = true;
  };

  async continueGame(){
    // check one more time if the user may continue
    if(!this.mayContinue){
      this.alert.presentToast("Give to all the cards a value first");
      return;
    }

    this.alert.showLoader("Please wait");
    // remove all the cards with value false from array
    for(var i = 0; i < this.game.cardset.length; i++){
      const card = this.game.cardset[i];
      if(card.value == 2){
        this.game.cardset.splice(i,1);
        i--;
      }
    }

    // set storage and go to the next page
    this.alert.hideLoader();

    if(this.game.cardset.length < 5){
      let addvalues = await this.alert.presentAlertConfirm("Missing values?", "Do you want to add values to the list?", "yes", "no");
      this.nextGame = addvalues == "yes" ? "Add" : "Ranking";
    }else{
      this.nextGame = "Ranking";
    }

    await this.game.saveGameStorage("Values", this.nextGame, this.game.cardset);

    this.router.navigateByUrl(`/values${this.nextGame}`);
  }
}
