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

const testGame = require('./../test.game');
const testInstance = require('./../test.instance');

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

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

        return {
            account,
            instances,
            team,
            cryps,
            game,
            sendInstanceState,
        };
    },
    function receiveDispatch(dispatch) {
        function setTestGame(id) {
            return dispatch(actions.setGame(testGame(id)));
        }

        function setTestInstance(id) {
            return dispatch(actions.setInstance(testInstance(id)));
        }

        function navTo(place) {
            dispatch(actions.setGame(null));
            dispatch(actions.setInstance(null));
            return dispatch(actions.setNav(place));
        }

        return {
            setTestGame,
            setTestInstance,
            navTo,
        };
    }
);

function Nav(args) {
    const {
        account,
        sendInstanceState,
        team,
        cryps,
        instances,
        game,

        navTo,
        setTestGame,
        setTestInstance,
    } = args;

    function joinInstance(i) {
        if (game) navTo(null);
        sendInstanceState(i);
        return true;
    }

    const joined = instances.map(i => (
        <button key={i.id} onClick={() => joinInstance(i)} >{i.name}</button>
    ));

    const teamElements = team.map((c, i) => {
        if (c) {
            const cryp = cryps.find(f => f.id === c);
            return <button key={c} onClick={() => navTo('team')}>{cryp.name}</button>;
        }
        return <button key={i} onClick={() => navTo('team')}>+</button>;
    });

    return (
        <nav>
            <h2>Team</h2>
            {teamElements}
            <h2>Instances</h2>
            <button onClick={() => navTo('team')}>1. Select Team</button>
            <button onClick={() => navTo('list')}>2. Join</button>
            <hr />
            {joined}
            <h2>Hax</h2>
            <button onClick={() => setTestGame(account.id)}>Test Game</button>
            <button onClick={() => setTestInstance(account.id)}>Test Instance</button>
        </nav>
    );
}

module.exports = addState(Nav);
