import Utils from './utils/Utils';
import anime from 'animejs';

class Cursor {
    constructor() {
        this.mousePos = { x: window.innerWidth / 2, y: window.innerHeight / 2 };
        this.pointer = {
            DOM: document.querySelector('.cursor'),
            mousepos: { x: 0, y: 0 },
            scale: { previous: 0, current: 0 },
            opacity: { previous: 0, current: 0 }
        };
        this.states = {
            'header': { width: 90,  height: 209, elements: [document.querySelector('.cursorIcon--header')] },
            'drag':   { width: 322, height: 80, elements: [document.querySelector('.cursorIcon--drag')]  },
            'popin':  { width: 86, height: 14, elements: [document.querySelector('.cursorIcon--popin-close')]  }
        };
        if (!this.isTouch()) { requestAnimationFrame(() => this.render()); }
    }
    render() {
        this.pointer.mousepos = {
            x: Utils.lerp(this.pointer.mousepos.x, this.mousePos.x, 1),
            y: Utils.lerp(this.pointer.mousepos.y, this.mousePos.y, 1)
        };

        this.pointer.scale.previous = Utils.lerp(this.pointer.scale.previous, this.pointer.scale.current, 0.25);
        this.pointer.opacity.previous = Utils.lerp(this.pointer.opacity.previous, this.pointer.opacity.current, 0.15);

        anime.set(this.pointer.DOM, {
            translateX: this.pointer.mousepos.x,
            translateY: this.pointer.mousepos.y,
            scale: this.pointer.scale.previous,
            opacity: this.pointer.opacity.previous
        });

        requestAnimationFrame(() => this.render());
    }
    updatePos(pos) {
        if (this.isTouch()) return;
        
        this.mousePos = pos;
    }
    hide() {
        if (this.isTouch()) return;
        document.getElementsByTagName('html')[0].removeAttribute('cursor-active');
        this.pointer.DOM.removeAttribute('data-cursor');
        this.pointer.scale.current = 0;
        this.pointer.opacity.current = 0;
        
        let states = Object.keys(this.states);
        states.forEach((state) => {
            this.states[state].elements.forEach((elt) => {
                anime.set(elt, { opacity: 0 });
            });
        });
    }
    show(state) {
        if (this.isTouch()) return;

        document.getElementsByTagName('html')[0].setAttribute('cursor-active', 'true');
        this.pointer.DOM.setAttribute('data-cursor', state);
        this.pointer.scale.current = 1;
        this.pointer.opacity.current = 1;
        this.states[state].elements.forEach((elt) => {
            anime.set(elt, { opacity: 1 });
        });
    }
    isTouch() {
        return 'ontouchstart' in document.documentElement;
    }
}

export default Cursor;