const { connect } = require('react-redux');
const preact = require('preact');

const { NULL_UUID } = require('./../utils');
const actions = require('./../actions');
const InstanceCreateForm = require('./instance.create.form');

const addState = connect(
    function receiveState(state) {
        const { ws, cryps, team, instances, account } = state;

        function sendInstanceJoin(instance) {
            if (team.length) {
                return ws.sendInstanceJoin(instance.id, team);
            }
            return false;
        }

        function sendInstanceState(instance) {
            return ws.sendInstanceState(instance.id);
        }

        function sendInstanceList() {
            return ws.sendAccountInstances();
        }

        return {
            account,
            cryps,
            team,
            sendInstanceJoin,
            sendInstanceState,
            sendInstanceList,
            instances,
        };
    },
);

function List(args) {
    const {
        account,
        team,
        sendInstanceState,
        sendInstanceJoin,
        sendInstanceList,
        instances,
    } = args;

    function instanceList() {
        if (!instances) return <div>...</div>;

        const instancePanels = instances.map(instance => {
            const player = instance.players.find(p => p.id === account.id);
            const scoreText = player
                ? `${player.score.wins} : ${player.score.losses}`
                : '';

            function instanceClick() {
                if (!player) return sendInstanceJoin(instance);
                return sendInstanceState(instance);
            }

            return (
                <tr key={instance.id}
                    className="right"
                    onClick={instanceClick} >
                    <td>{instance.name}</td>
                    <td>{instance.players.length} / {instance.max_players}</td>
                    <td>{scoreText}</td>
                </tr>
            );
        });

        return (
            <div className="menu-instance-list" >
                <table>
                    <thead>
                        <tr>
                            <th>instance name</th>
                            <th>players</th>
                            <th>status</th>
                        </tr>
                    </thead>
                    <tbody>
                        {instancePanels}
                        <tr className="right" onClick={() => sendInstanceList()}>
                            <td colSpan={3} >↺</td>
                        </tr>
                    </tbody>
                </table>
                <InstanceCreateForm />
            </div>
        );
    }

    return (
        <main className="menu">
            {instanceList()}
        </main>
    );
}

module.exports = addState(List);
