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

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

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

        function mtxBuy(mtx) {
            return ws.sendMtxBuy(mtx.variant);
        }

        return {
            account,
            shop,
            mtxBuy,
        };
    },

    function receiveDispatch(dispatch) {
        function setMtxActive(mtx) {
            dispatch(actions.setConstructRename(null));
            dispatch(actions.setMtxActive(mtx));
            return true;
        }

        return {
            setMtxActive,
        };
    }
);

function Inventory(args) {
    const {
        account,
        shop,
        setMtxActive,
        mtxBuy,
    } = args;

    if (!shop) return false;

    const useMtx = (item, i) => (
        <figure key={i} onClick={() => setMtxActive(item)} >
            <figcaption>{item}</figcaption>
            <button>¤1</button>
        </figure>
    );

    const availableMtx = (item, i) => (
        <figure key={i} onClick={() => mtxBuy(item)} >
            <figcaption>{item.variant}</figcaption>
            <button>¤{item.credits}</button>
        </figure>
    );

    return (
        <div class="inventory">
            <div>
                <h1>¤ {account.balance}</h1>
                <div class='list'>
                    {shop.owned.map(useMtx)}
                </div>
            </div>
            <div>
                <h1>Shop</h1>
                <div class='list'>
                    {shop.available.map(availableMtx)}
                </div>
            </div>
        </div>
    );
}

module.exports = addState(Inventory);
