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,
            activeConstruct,
        } = state;

        function selectSkillTarget(targetConstructId) {
            if (activeSkill) {
                return ws.sendGameSkill(game.id, activeSkill.constructId, targetConstructId, 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.constructId, null, activeSkill.skill.skill);
        }

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

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

        function setActiveConstruct(construct) {
            dispatch(actions.setActiveConstruct(construct));
        }

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

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

        function skip() {
            dispatch(actions.setSkip(true));
        }

        return { setActiveSkill, setActiveConstruct, quit, toggleLog, skip };
    }

);

module.exports = addState(Game);
