import { client, lang } from "../index.js";
import AbstractAuthenticatedView from "./abstracts/AbstractAuthenticatedView.js";

export default class extends AbstractAuthenticatedView
{
    constructor(params)
	{
        super(params, 'homeWindowTitle');
        this.id = params.id;
	}

    async postInit()
    {
        this.profile = await client.profiles.getProfileId(this.id);

        if (this.profile === null)
            return 404;

        await this.fillHistory();
    }

    async fillHistory()
    {
        let games = await this.profile.getGameHistory();

        let game_list = document.getElementById("game-list");

        games.forEach(game => {

            let a = document.createElement("a");
            a.href = `/games/${game.id}/0`;
            a.setAttribute("data-link", true);

            let game_item = document.createElement("div");
            game_item.className = "game-item";
            game_item.style.backgroundColor = "grey";
            if (game.started)
                game_item.style.backgroundColor = "yellow";
            if (game.finished)
                game_item.style.backgroundColor = this.profile.id === game.winner_id ? "green" : "red";

            game.players.forEach(player => {
                let player_score = document.createElement("a");

                player_score.href = `/profiles/${player.username}`;
                player_score.innerText = `${player.username}: ${player.score.length}`;
                player_score.setAttribute("data-link", true);

                game_item.appendChild(player_score);
            });

            a.appendChild(game_item);
            game_list.appendChild(a);
        });
    }

    async getHtml()
	{
        return /* HTML */ `
            <link rel="stylesheet" href="/static/css/gameHistory.css">
            <h1>Game History</h1>
            <div id="game-list">
            </div>
        `;
    }
}
