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

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

const addState = connect(
    function receiveState(state) {
        const {
            activeSkill,
            game,
        } = state;

        return {
            activeSkill,
            game,
        };
    },

    function receiveDispatch(dispatch) {
        function setActiveSkill(constructId, skill) {
            dispatch(actions.setActiveSkill(constructId, skill));
        }

        return { setActiveSkill };
    }
);


function Skill(props) {
    const {
        construct,
        game,
        i,
        activeSkill,
        setActiveSkill,
    } = props;

    const s = construct.skills[i];
    const ko = construct.green_life.value === 0 ? 'ko' : '';

    if (!s) {
        return (
            <button
                disabled='true'
                class='construct-skill-btn disabled'>
            </button>
        );
    }

    // const skillChosen = game.stack.some(stack => stack.source_construct_id === construct.id);
    const targeting = game.stack.some(stack => stack.source_construct_id === construct.id && stack.skill === s.skill);

    // if (skillChosen && !targeting) {
    //     return false;
    // }

    const cdText = construct.skills[i].cd > 0
        ? `- ${s.cd}T`
        : '';

    const highlight = activeSkill
        ? activeSkill.constructId === construct.id && activeSkill.skill === s.skill
        : false;

    function onClick(e) {
        e.stopPropagation();
        return setActiveSkill(construct.id, s.skill);
    }

    return (
        <button
            disabled={cdText || s.disabled || ko}
            class={`construct-skill-btn ${(targeting || highlight) ? 'active' : ''}`}
            type="submit"
            onClick={onClick}>
            {s.skill} {cdText}
        </button>
    );
}

module.exports = addState(Skill);
