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

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

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

        return {
            activeSkill,
        };
    },

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

        return { setActiveSkill };
    }
);


function Skill(props) {
    const {
        cryp,
        i,
        mobile,
        activeSkill,
        setActiveSkill,
    } = props;

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

    if (!s) {
        return (
            <button
                disabled='true'
                className='cryp-skill-btn disabled'>
                <span>&nbsp;</span>
            </button>
        );
    }

    const side = mobile
        ? 'top'
        : 'right';

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

    const highlight = activeSkill
        ? activeSkill.crypId === cryp.id && activeSkill.skill === s
        : false;

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

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

module.exports = addState(Skill);
