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

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

const { ConstructAvatar } = require('./construct');
const Controls = require('./controls');

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

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

        return {
            instance,
            account,
            sendInstanceReady,
        };
    },
);

function FaceoffConstruct(args) {
    const {
        construct
    } = args;

    return (
        <div class='game-construct'>
            <div class="left"></div>
            <div class="right">
                <h3 class="name"> {construct.name} </h3>
                <ConstructAvatar construct={construct} />
            </div>
        </div>
    )
}

function Faceoff(props) {
    const {
        instance,
        account,
        sendInstanceReady,
    } = props;

    if (!instance) return <div>...</div>;

    const otherTeam = instance.players.find(t => t.id !== account.id);
    const playerTeam = instance.players.find(t => t.id === account.id);

    function PlayerTeam(team) {
        const constructs = team.constructs.map((c, i) =>
            <FaceoffConstruct key={c.id} construct={c}/>);

        const classes = `team player ${team.ready ? 'ready' : ''}`
        return (
            <div class={classes}>
                {constructs}
            </div>
        );
    }

    function OpponentTeam(team) {
        const constructs = team.constructs.map((c, i) =>
            <FaceoffConstruct key={c.id} construct={c}/>);

        const classes = `team opponent ${team.ready ? 'ready' : ''}`

        return (
            <div class={classes}>
                {constructs}
            </div>
        );
    }

    return (
        <main class="faceoff">
            {OpponentTeam(otherTeam)}
            {PlayerTeam(playerTeam)}
        </main>
    );
}

module.exports = addState(Faceoff);
