const preact = require('preact');
const { connect } = require('preact-redux');
const reactStringReplace = require('react-string-replace');

const actions = require('../actions');
const shapes = require('./shapes');
const { INFO } = require('./../constants');

const addState = connect(
    ({ resolution, itemInfo, gameSkillInfo }) => ({ resolution, itemInfo, gameSkillInfo }),

    function receiveDispatch(dispatch) {
        function setGameEffectInfo(info) {
            dispatch(actions.setGameEffectInfo(info));
        }

        return { setGameEffectInfo };
    }

);

class GameConstructEffects extends preact.Component {
    shouldComponentUpdate(newProps) {
        if (newProps.resolution && newProps.resolution !== this.props.resolution) {
            const [type, info] = newProps.resolution.event;
            if (info.construct === this.props.construct.id
                && (type === 'Effect' || type === 'Removal')) return true;
        }
        if (newProps.construct !== this.props.construct) return true;
        return false;
    }

    render() {
        const {
            resolution,
            construct,
            gameSkillInfo,
            setGameEffectInfo,
            itemInfo,
        } = this.props;

        function hoverInfo(e, info) {
            e.stopPropagation();
            return setGameEffectInfo(info);
        }
        if (gameSkillInfo && gameSkillInfo.constructId === construct.id) {
            const fullInfo = itemInfo.items.find(k => k.item === gameSkillInfo.skill) || INFO[gameSkillInfo.skill];
            const regEx = /(RedPower|BluePower|GreenPower|RedLife|BlueLife|GreenLife|SpeedStat)/;
            const infoDescription = reactStringReplace(fullInfo.description, regEx, match => shapes[match]());
            const speed = <span> Speed {shapes.SpeedStat()} multiplier {fullInfo.speed * 4}% </span>;
            return (
                <div class="skill-description">
                    <h2><span> {gameSkillInfo.skill} </span></h2>
                    <span>{infoDescription} </span> <br />
                    {speed}
                </div>);
        }

        const effects = resolution ? resolution.event[1].display.effects : construct.effects;

        const renderEffects = effects.length
            ? effects.map(c =>
                <div key={c.effect}>
                    <span key={c.effect} onMouseOver={e => hoverInfo(e, c)}
                        onMouseOut={e => hoverInfo(e, null)}> {c.effect} - {c.duration}T
                    </span>
                </div>)
            : null;
        return (<div class="effects"> {renderEffects} </div>);
    }
}

module.exports = addState(GameConstructEffects);
