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

const Vbox = require('./vbox.component');
const InfoContainer = require('./info.container');
const InstanceConstructsContainer = require('./instance.constructs');
const EquipmentContainer = require('./instance.equip');

const actions = require('../actions');

const addState = connect(
    function receiveState(state) {
        const { ws, instance, nav } = state;
        return { instance, nav };
    },

    function receiveDispatch(dispatch) {
        function setInfo(c) {
            return dispatch(actions.setInfo(c));
        }

        return {
            setInfo,
        };
    }
);

function Instance(args) {
    const {
        instance,
        setInfo,

        nav,
    } = args;

    if (!instance) return false;

    function playerRound(id) {
        if (!instance.rounds.length) return null;
        return instance.rounds[instance.rounds.length - 1].find(r => r.player_ids.includes(id));
    }

    function playerText(p) {
        const round = playerRound(p.id);
        if (!round) {
            return p.ready
                ? 'ready'
                : '';
        }

        if (round.finished) return 'finished';
        if (round.game_id) return 'in game';

        return p.ready
            ? 'ready'
            : '';
    }

    function ScoreBoard() {
        if (instance.phase !== 'Lobby') return null;

        const players = instance.players.map((p, i) => {
            const pText = playerText(p);
            return (
                <tr key={i}
                    className={p.ready ? 'ready' : ''}>
                    <td>{p.name}</td>
                    <td>{p.score.wins} / {p.score.losses}</td>
                    <td>{pText}</td>
                </tr>
            );
        });

        return (
            <table className="scoreboard" >
                <tbody>
                    {players}
                </tbody>
            </table>
        );
    }

    const instanceClasses = `instance ${nav === 'constructs' ? 'constructs-visible' : ''}`;

    return (
        <main className={instanceClasses} onMouseOver={() => setInfo(null)} >
            <ScoreBoard />
            <Vbox />
            <InfoContainer />
            <EquipmentContainer />
            <InstanceConstructsContainer />
        </main>
    );
}

module.exports = addState(Instance);
