import { client, navigateTo } from "../index.js";
import { clear, fill_errors } from "../utils/formUtils.js";
import AbstractAuthenticatedView from "./abstracts/AbstractAuthenticatedView.js";

export default class extends AbstractAuthenticatedView {

    constructor(params)
    {
        super(params, "Matchmaking");
    }

    async press_button()
    {
        clear("innerText", ["detail"]);
        if (client.matchmaking.searching)
        {
            client.matchmaking.stop();
            document.getElementById("button").value = "Find a game";
        }
        else
        {
            let nb_players = document.getElementById("nb_players-input").value;

            await client.matchmaking.start(this.onreceive.bind(this), this.ondisconnect.bind(this), nb_players);

            document.getElementById("button").value = "Stop matchmaking";
        }
    }

    ondisconnect(event)
    {
        document.getElementById("button").value = "Find a game";
    }

    onreceive(data)
    {
        if (data.detail === "game_found")
        {
            navigateTo(`/games/${data.game_id}`);
            return;
        }
        this.display_data(data);
    }

    display_data(data)
    {
        clear("innerText", ["detail"]);
        fill_errors(data, "innerText");
    }

    async postInit()
    {
        let button = document.getElementById("button");
        
        button.onclick = this.press_button.bind(this);

        let input = document.getElementById("nb_players-input");

        input.addEventListener('keydown', async ev => {
            if (ev.key !== 'Enter')
                return;

            if (client.matchmaking.searching)
                client.matchmaking.stop();
            
            let nb_players = document.getElementById("nb_players-input").value;
    
            await client.matchmaking.start(this.onreceive.bind(this), this.ondisconnect.bind(this), nb_players);
    
            document.getElementById("button").value = "Stop matchmaking";
        });

        let update = () => {
            if (input.value < 2)
                button.disabled = true;
            else
                button.disabled = false;
        };

        ["change", "oninput"].forEach((event_name) => {
            input.addEventListener(event_name, update);
        });
    }

    async getHtml() {
        return `
			<h1>Select mode</h1>
            <input type="number" value="2" min="1" id="nb_players-input">
            <input type="button" value="Find a game" id="button">
            <span id="detail"></span>
        `;
    }

    async leavePage()
    {
		await client.matchmaking.stop();
    }
}
