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

const shapes = require('./shapes');
const { removeTier } = require('../utils');
const { TIMES } = require('./../constants');

const addState = connect(({ animText, itemInfo }) => ({ animText, itemInfo }));

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

    componentDidUpdate(prevProps) {
        const { animText, construct } = this.props;
        if (animText && animText !== prevProps.animText && animText.constructId === construct.id) {
            anime({
                targets: '.combat-text',
                top: '40%',
                duration: TIMES.POST_SKILL_DURATION_MS - 500,
                easing: 'easeOutQuad',
            });
        }
    }

    render(props) {
        const { construct, animText, itemInfo } = props;
        if (animText && animText.constructId === construct.id) {
            const itemSourceDescription = () => {
                const itemSource = itemInfo.combos.filter(c => c.item === removeTier(animText.skill));
                const itemSourceInfo = itemSource.length
                    ? `${itemSource[0].components[0]} ${itemSource[0].components[1]} ${itemSource[0].components[2]}`
                    : false;
                const itemRegEx = /(Red|Blue|Green)/;
                return reactStringReplace(itemSourceInfo, itemRegEx, match => shapes[match]());
            };

            const animationTextHtml = () => {
                // monkaW hack to make red / blue recharge work nicely
                if (animText.css === 'rb') {
                    const text = animText.text.split(' ');
                    return (
                        <h1>
                            <span class="red">{text[0]}</span>&nbsp;
                            <span class="blue">{text[1]}</span>
                        </h1>
                    );
                }
                return (
                    <h1 class={animText.css}>
                        <span>{animText.text}</span>
                    </h1>
                );
            };


            return (
                <div class="combat-text">
                    <h2><span>{animText.skill}</span></h2>
                    <span>{itemSourceDescription()}</span>
                    {animationTextHtml()}
                </div>
            );
        }
        return null;
    }
}

module.exports = addState(AnimText);
