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

const molecule = require('./molecule');
const actions = require('../actions');
const { STATS, eventClasses, getCombatText } = require('../utils');

const SkillBtn = require('./skill.btn');

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

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

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

        return {
            resolution,
            activeSkill,
            activeCryp,
            selectSkillTarget,
        };
    },

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

        return { setActiveCryp };
    }
);


function GameCryp(props) {
    const {
        cryp,
        resolution,

        activeSkill,
        setActiveCryp,
        selectSkillTarget,
    } = props;

    const ko = cryp.green_life.value === 0 ? 'ko' : '';

    const classes = eventClasses(resolution, cryp);

    const skills = range(0, 3)
        .map(i => <SkillBtn key={i} cryp={cryp} i={i} />);

    const stats = [STATS.greenLife, STATS.redLife, STATS.blueLife].map((s, j) => (
        <figure key={j} alt={s.stat}>
            {s.svg(`stat-icon ${s.colour}`)}
            <figcaption>{cryp[s.stat].value} / {cryp[s.stat].max}</figcaption>
        </figure>
    ));


    function onClick(e) {
        e.stopPropagation();
        return setActiveCryp(cryp);
    }

    const combatText = getCombatText(cryp, resolution);

    return (
        <div
            style={ activeSkill ? { cursor: 'pointer' } : {}}
            onClick={onClick}
            className={`cryp-box ${ko} ${classes}`} >
            <div className="cryp-box-top">
                <figure
                    className="img"
                    onClick={() => selectSkillTarget(cryp.id)} >
                    {molecule(combatText)}
                    <figcaption>{cryp.name}</figcaption>
                </figure>
                <div className="skills">
                    {skills}
                </div>
            </div>
            <div className="stats">
                {stats}
            </div>
        </div>
    );
}

module.exports = addState(GameCryp);
