const preact = require('preact');
const { Component } = require('preact');
const anime = require('animejs').default;
const times = require('lodash/times');
const { connect } = require('preact-redux');

const { TIMES, COLOURS } = require('../../constants');

const addState = connect(
    function receiveState(state) {
        const { animCb } = state;
        return { animCb };
    }
);

class Decay extends Component {
    constructor() {
        super();
        this.animations = [];
    }

    render() {
        return (
            <svg
                id="decay"
                class="skill-animation"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 300 300">
                <g>
                    {times(20, () => (
                        <rect x="135" y="135" width="10" height="10" />
                    ))}
                </g>
            </svg>
        );
    }

    componentDidMount() {
        this.animations.push(anime({
            targets: ['#decay'],
            opacity: [
                { value: 1, delay: TIMES.TARGET_DELAY_MS, duration: TIMES.TARGET_DURATION_MS * 0.2 },
                { value: 0, delay: TIMES.TARGET_DURATION_MS * 0.6, duration: TIMES.TARGET_DURATION_MS * 0.2 },
            ],
            easing: 'easeInOutSine',
        }));

        this.animations.push(anime({
            targets: ['#decay rect'],
            stroke: [COLOURS.WHITE, COLOURS.BLUE],
            strokeWidth: [4, 2],
            transform: () => `
                translate(${anime.random(-120, 120)} ${anime.random(-120, 120)})
                rotate(${anime.random(-15, 15)})
            `,
            easing: 'easeOutSine',
            delay: TIMES.TARGET_DELAY_MS,
            duration: TIMES.TARGET_DURATION_MS,
        }));
    }

    // this is necessary because
    // skipping / timing / unmounting race conditions
    // can cause the animations to cut short, this will ensure the values are reset
    // because preact will recycle all these components
    componentWillUnmount() {
        for (let i = this.animations.length - 1; i >= 0; i--) {
            this.animations[i].reset();
        }
        this.props.animCb && this.props.animCb();
    }
}

module.exports = addState(Decay);
