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

const { ConstructAvatar, ConstructName } = require('./construct');

const SkillBtn = require('./game.construct.skill.btn');
const ConstructAnimationText = require('./game.construct.anim.text');
const ConstructLife = require('./game.construct.life');
const ConstructEffectBox = require('./game.construct.effect.box');

const addState = connect(
    function receiveState(state) {
        const {
            ws,
            game,

            activeSkill,
            animFocus,
            animText,
        } = state;

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

        return {
            activeSkill,
            animFocus,
            animText,
            selectSkillTarget,
        };
    }
);

class GameConstruct extends preact.Component {
    shouldComponentUpdate(newProps) {
        if (newProps.activeSkill !== this.props.activeSkill) return true;
        if (newProps.animFocus !== this.props.animFocus) return true;
        if (newProps.animText !== this.props.animText) return true;
        if (newProps.construct !== this.props.construct) return true;
        return false;
    }

    render() {
        const {
            // Changing state variables
            activeSkill,
            animFocus,
            animText,
            selectSkillTarget,
            construct,
            player,
        } = this.props;

        const koEvent = animText && animText.text === 'KO!' && animText.constructId === construct.id;
        const ko = construct.green_life.value === 0 && !koEvent ? 'ko' : '';

        const cssClass = () => {
            if (koEvent) return 'ko-transition';
            if (animFocus && !animFocus.includes(construct.id)) return 'unfocus';
            return '';
        };

        const crypSkills = player
            ? <div class="skills"> {range(0, 3).map(j => <SkillBtn key={j} construct={construct} i={j} />)} </div>
            : <div></div>;


        return (
            <div
                onClick={() => selectSkillTarget(construct.id)}
                style={ activeSkill ? { cursor: 'pointer' } : {}}
                class={`game-construct ${ko} ${cssClass()}`}>
                <div class="left">
                    {crypSkills}
                    <ConstructEffectBox construct={construct} />
                </div>
                <div class="right">
                    <ConstructLife construct={construct} />
                    <ConstructAvatar construct={construct} />
                    <ConstructName construct={construct} />
                    <ConstructAnimationText construct={construct} />
                </div>
            </div>
        );
    }
}

module.exports = addState(GameConstruct);
