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";

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

	keyStretchHandler(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);
	}

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

        if (canva === null)
            return 1;

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

        ctx.beginPath();

        this.game.draw(ctx);

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

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

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

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

    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_gool,
                                          my_player.position,
                                        );
            this.game.players[index] = this.my_player;
        }

        this.register_key()

        this.render_game();
    }

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

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

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

        if (error_code)
            return error_code;

        await this.update_game_state();
	}

    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>
            <div id="player_list"></div>
        `;
    }
}
