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

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

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

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

    render() {
        // const { x, y } = (this.props && this.props.direction) || { x: 0, y: 0 };
        // const angle = (Math.atan(y / x) * (180 / Math.PI)) + 90;
        // console.log(x, -y);
        // console.log(angle);
        // can't get this shit to work

        return (
            <svg
                class="strike-anim"
                version="1.1"
                id="strike"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 400 400">
                <filter id='strikeFilter'>
                    <feTurbulence type="turbulence" baseFrequency="0" numOctaves="1" result="turbulence"></feTurbulence>
                    <feDisplacementMap in2="turbulence" in="SourceGraphic" scale="1" xChannelSelector="R" yChannelSelector="G"></feDisplacementMap>
                </filter>
                <g>
                    <rect x="200" y="400"
                        width="12" height="100" stroke-width="0" fill={COLOURS.RED} style={{ filter: 'url("#strikeFilter")' }}
                    />
                </g>
            </svg>
        );
    }

    componentDidMount() {
        this.animations.push(anime({
            targets: ['#strike rect'],
            easing: 'easeOutExpo',
            y: [800, 100, 100],
            x: [200, 0, 200],
            height: [200, 10, 0],
            width: [20, 400, 0],
            delay: TIMES.TARGET_DELAY_MS * 0.5,
            duration: TIMES.TARGET_DURATION_MS,
        }));

        this.animations.push(anime({
            targets: ['#strikeFilter feTurbulence', '#strikeFilter feDisplacementMap'],
            baseFrequency: 2,
            scale: 50,
            numOctaves: 5,
            easing: 'easeOutSine',
            delay: TIMES.TARGET_DELAY_MS + (TIMES.TARGET_DURATION_MS / 3),
            duration: TIMES.TARGET_DURATION_MS / 2,
        }));
    }

    // 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(Strike);
