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

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

const GREEN = '#1FF01F';
const RED = '#a52a2a';

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

    render() {
        return (
            <svg
                class={'skill-animation'}
                version="1.1"
                id="slay"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 300 300">
                {times(10, () => (
                    <ellipse
                        cx={anime.random(100, 200)}
                        cy={anime.random(-60, -30)}
                        stroke="none"
                        rx={anime.random(5, 10)}
                        ry={10}
                        fill={RED}
                    />
                ))}
            </svg>
        );
    }

    componentDidMount() {
        let rotate = 0; // Self target value
        if (this.props.direction.y) {
            if (!this.props.direction.x) rotate = this.props.direction.y > 0 ? 0 : 180;
            else {
                rotate = this.props.direction.y > 0
                    ? -Math.atan(this.props.direction.y / this.props.direction.x) * 180 / Math.PI
                    : -Math.atan(this.props.direction.y / this.props.direction.x) * 180 / Math.PI + 180;
            }
        } else if (this.props.direction.x) {
            rotate = this.props.direction.x > 0 ? 270 : 90;
        }

        anime.set('#slay', {
            rotate,
            opacity: 1,
        });

        anime.set('#slay ellipse',{
            fill: RED,
        })

        this.animations.push(anime({
            targets: ['#slay ellipse'],
            cx: 150,
            cy: 325,
            duration: TIMES.TARGET_DURATION_MS * 0.2,
            duration: TIMES.TARGET_DURATION_MS * 0.4,
            easing: 'easeOutQuad',
            direction: 'alternate',
        }));

        setTimeout(() => anime.set('#slay ellipse',{
            fill: GREEN,
        }), TIMES.TARGET_DURATION_MS * 0.5);
    }

    componentWillUnmount() {
        for (let i = this.animations.length - 1; i >= 0; i--) {
            this.animations[i].reset();
        }
    }
}

module.exports = Slay;
