import { client } from "../index.js";
import { Game } from "../api/game/Game.js";
import AbstractView from "./abstracts/AbstractView.js";
import { MyPlayer } from "../api/game/MyPlayer.js";
import { lang } from "../index.js";

export default class extends AbstractView
{
    constructor(params)
	{
        super(params, "Game");
        this.game = new Game(client, params.id, this.update_goal);
        this.keys_pressed = [];
        this.my_player = undefined;
    }

	keyReleaseHandler(event)
    {
		const idx = this.keys_pressed.indexOf(event.key);
		if (idx != -1)
			this.keys_pressed.splice(idx, 1);
	}

    keyPressHandler(event)
    {
		if (!this.keys_pressed.includes(event.key))
			this.keys_pressed.push(event.key);
	}

    render_game()
    {
        const canva = document.getElementById('canva');

        if (canva === null)
            return 1;

        /**
         * @type {CanvasRenderingContext2D}
         */
        let ctx = canva.getContext('2d');

        ctx.beginPath();

        this.game.render(ctx);

        ctx.strokeStyle = "#000000";
        ctx.lineWidth = 1;
        ctx.stroke();
    }

    /**
     * @param {Object} data 
     */
    update_goal(data)
    {
        document.getElementById(`goal-${data.player}`).innerText = data.nb_goal;
    }

    render()
    {
        let loop_id = setInterval(() => {
            if (this.game === undefined)
                clearInterval(loop_id);
            if (this.my_player)
                this.my_player.update_paddle(this.keys_pressed);
            this.render_game();
            this.game?.time.new_frame();
            //clearInterval(loop_id);
        // 1 sec  fps
        }, 1000 / 60);
    }

    register_key()
    {
		this.keyPressHandler = this.keyPressHandler.bind(this);
		this.keyReleaseHandler = this.keyReleaseHandler.bind(this);
        document.addEventListener('keydown', this.keyPressHandler);
		document.addEventListener('keyup', this.keyReleaseHandler);
    }

    unregister_key()
    {
        document.removeEventListener('keydown', this.keyPressHandler);
		document.removeEventListener('keyup', this.keyReleaseHandler);
    }

    async join_game()
    {
        await this.game.join();

        let canva = document.createElement("canvas");

        canva.height = this.game.config.size_x;
        canva.width = this.game.config.size_y;
        canva.id = "canva"; 

        document.getElementById("app").appendChild(canva);

        let index = this.game.players.findIndex((player) => player.id === client.me.id);
        if (index !== -1)
        {
            let my_player = this.game.players[index];
            this.my_player = new MyPlayer(client,
                                          this.game,
                                          my_player.rail,
                                          my_player.nb_goal,
                                          my_player.position,
                                        );
            this.game.players[index] = this.my_player;
        }

        this.register_key();

        this.render();
    }

    async update_game_state()
    {
        document.getElementById("game-state").innerText = this.game.state;

        if (this.game.finished === false)
            await this.join_game();
    }

    display_players_list()
    {
        let players_list = document.getElementById("players_list");

        this.game.players.forEach(player => {

            let tr = document.createElement("tr");
            let name = document.createElement("td");
            let goal = document.createElement("td");
            
            name.id = `username-${player.id}`;
            goal.id = `goal-${player.id}`;

            name.innerText = player.username;
            goal.innerText = player.nb_goal;

            tr.appendChild(name);
            tr.appendChild(goal);

            players_list.appendChild(tr);
        });
    }

	async postInit()
	{
		let error_code = await this.game.init();

        if (error_code)
            return error_code;

        await this.update_game_state();
        this.display_players_list();
	}

    async leavePage()
    {
        if (this.game.finished === false)
        {
            this.game.leave();
            this.game = undefined;
        }
        this.unregister_key();
    }

    async getHtml()
	{
        return /* HTML */ `
            <link rel="stylesheet" href="/static/css/game.css">
            <h2 id="game-state"></h2>

            <table>
                <thead>
                    <tr>
                        <th scope="col">${lang.get("gamePlayersListName")}</th>
                        <th scope="col">${lang.get("gameGoalTaken")}</th>
                    </tr>
                </thead>
                <tbody id="players_list">
                </tbody>
            </table>
        `;
    }
}
