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

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

const Game = require('./game.component');

const addState = connect(
    function receiveState(state) {
        const {
            ws,
            game,
            account,
            resolution,
            showLog,
            activeSkill,
            activeCryp,
        } = state;

        function selectSkillTarget(targetCrypId) {
            if (activeSkill) {
                return ws.sendGameSkill(game.id, activeSkill.crypId, targetCrypId, activeSkill.skill);
            }
            return false;
        }

        function sendGameReady() {
            ws.sendGameReady(game.id);
        }

        function sendInstanceState(instanceId) {
            if (!instanceId) return false;
            return ws.sendInstanceState(instanceId);
        }

        // intercept self casting skills
        if (activeSkill && activeSkill.skill.self_targeting) {
            ws.sendGameSkill(game.id, activeSkill.crypId, null, activeSkill.skill.skill);
        }

        return {
            game,
            showLog,
            account,
            resolution,
            activeSkill,
            activeCryp,
            selectSkillTarget,
            sendInstanceState,
            sendGameReady,
        };
    },

    function receiveDispatch(dispatch) {
        function setActiveSkill(crypId, skill) {
            dispatch(actions.setActiveSkill(crypId, skill));
            // particlesJS(`particles-${crypId}`, config);
        }

        function setActiveCryp(cryp) {
            dispatch(actions.setActiveCryp(cryp));
        }

        function quit() {
            dispatch(actions.setGame(null));
            dispatch(actions.setInstance(null));
        }

        function toggleLog(v) {
            dispatch(actions.setShowLog(v));
        }


        return { setActiveSkill, setActiveCryp, quit, toggleLog };
    }

);

module.exports = addState(Game);
