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

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

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

const addState = connect(
    function receiveState(state) {
        const {
            ws,
            game,
            resolution,
            activeSkill,
        } = 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,
            selectSkillTarget,
        };
    },
);

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) => {
        // i've seen this happen ;/
        if (cryp[s.stat].value < 0) console.warn(cryp);
        return <figure key={j} alt={s.stat}>
            {s.svg(`stat-icon ${s.colour}`)}
            <figcaption>{cryp[s.stat].value} / {cryp[s.stat].max}</figcaption>
        </figure>
    });


    const combatText = getCombatText(cryp, resolution);
    const combatTextEl = combatText
        ? <div className="combat-text">{combatText}</div>
        : null;

    const effects = cryp.effects.length
        ? cryp.effects.map(c => <div key={c.effect}>{c.effect} - {c.duration}T</div>)
        : <div>&nbsp;</div>;

    return (
        <div
            style={ activeSkill ? { cursor: 'pointer' } : {}}
            className={`game-cryp ${ko} ${classes}`} >
            <div className="skills">
                {skills}
            </div>
            <div className="targeting">
                <div>{'< Decay'}</div>
                <div>{'< Attack'}</div>
                <div>{'< Sustain'}</div>
            </div>
            <figure
                className="img"
                onClick={() => selectSkillTarget(cryp.id)} >
                {crypAvatar(cryp.name)}
                {combatTextEl}
            </figure>
            <div className="effects">
                {effects}
            </div>
            <div className="stats">
                {stats}
            </div>
        </div>
    );
}

module.exports = addState(GameCryp);
