const Phaser = require('phaser');
const { TEXT, POSITIONS: { MENU_MAIN } } = require('./constants');

const X = MENU_MAIN.x();
const Y = MENU_MAIN.y();
const WIDTH = MENU_MAIN.width();
const HEIGHT = MENU_MAIN.height();
const ROW_SIZE = 50;
const LOBBY_WIDTH = WIDTH / 2;

class GameList extends Phaser.Scene {
    constructor() {
        super({ key: 'GameList' });
    }

    create(gameList) {
        this.cameras.main.setViewport(X, Y, WIDTH, HEIGHT);
        const ws = this.registry.get('ws');

        this.add.text(WIDTH / 3, 0, 'PVP open games', TEXT.HEADER);
        const gameRow = (game, i) => {
            const GAME_X = WIDTH / 6;
            const GAME_Y = 1.3 * ROW_SIZE * (i + 1);

            const gameBox = this.add
                .rectangle(GAME_X, GAME_Y, LOBBY_WIDTH, ROW_SIZE, 0x222222)
                .setInteractive()
                .setOrigin(0);

            const TITLE = `${game.teams[0].cryps.map(c => c.name).join(', ')} - ${game.team_size}v${game.team_size}`;

            this.add
                .text(gameBox.getCenter().x, gameBox.getCenter().y, TITLE, TEXT.NORMAL)
                .setOrigin(0.5, 0.5);

            gameBox.on('pointerdown', () => {
                const cryps = this.registry.get('cryps');
                const team = cryps.filter(c => c.active).map(c => c.id);
                ws.sendGameJoin(game.id, team);
            });
        };

        gameList.forEach(gameRow);

        return true;
    }

    cleanUp() {
        this.scene.remove();
    }
}

module.exports = GameList;
