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

const testGame = process.env.NODE_ENV === 'development' && require('./../test.game');
const testInstance = process.env.NODE_ENV === 'development' && require('./../test.instance');

console.log('env', process.env.NODE_ENV);

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

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

        return {
            account,
            instances,
            team,
            constructs,
            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,
        constructs,
        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 construct = constructs.find(f => f.id === c);
            return <button key={c} onClick={() => navTo('team')}>{construct.name}</button>;
        }
        return <button key={i} onClick={() => navTo('team')}>+</button>;
    });

    const haxSection = process.env.NODE_ENV === 'development'
        ? (
            <Fragment>
                <h2>Hax</h2>
                <button onClick={() => setTestGame(account.id)}>Test Game</button>
                <button onClick={() => setTestInstance(account.id)}>Test Instance</button>
            </Fragment>)
        : null;

    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}
            {haxSection}
        </nav>
    );
}

module.exports = addState(Nav);
