import { Constants } from "./Constants.js";
import { elt } from "./elt.js";
import { State } from "./State.js";

/**
 * Represents a game.
 */
export class Game
{
    /**
     * The state of the game.
     *
     * @type {State}
     */
    #state;

    /**
     * Initializes a new instance of the {@link Game `Game`} class.
     */
    constructor()
    {
        this.#state = new State();
    }

    /**
     * Gets the state of the game.
     */
    get state()
    {
        return this.#state;
    }

    /**
     * Gets the board of the game.
     */
    get board()
    {
        return this.state.board;
    }

    /**
     * Initializes the game.
     *
     * @param {string} id
     * The id of the element to add the board to.
     */
    initialize(id)
    {
        let board = document.getElementById(id);
        board.innerHTML = "";

        for (let i = 0; i < 6; i++)
        {
            for (let j = 0; j < 7; j++)
            {
                /** @type {Node[]} */
                let children = [];
                let playerId = this.board[i][j];

                if (playerId !== "")
                {
                    children.push(
                        elt(
                            "div",
                            {
                                class: `piece ${Constants.PLAYER_NAMES[playerId]}`
                            }));
                }

                let field = elt(
                    "div",
                    {
                        class: "field"
                    },
                    ...children);

                field.onclick = () =>
                {
                    this.board[i][j] = this.state.currentPlayer;
                    this.state.turnCount++;
                    this.initialize(id);
                };

                board.appendChild(field);
            }
        }
    }
}