export class CardTilter {

    /**
     *
     * @param card Card to be moved
     * @param tilt max tilting angle in degree
     * @param perspective perspective in pixels
     */
    constructor({card : card, tilt : tilt, perspective : perspective}) {
        this.card = card;
        this.tilt = tilt;
        this.perspective = perspective;
        this.watch()
    }

    watch(){
        this.card.addEventListener('mousemove', (e) => {
            const rect = this.card.getBoundingClientRect();
            const positions = this.calculatePositions(rect, e.clientX, e.clientY);
            const percentages = this.calculatePercentage(rect, positions.x, positions.y);

            this.transform(percentages.x, percentages.y);
        });

        this.card.addEventListener('mouseleave', () => {
            this.reset();
        });
    }

    calculatePositions(rect, cursorX, cursorY) {
        const x = cursorX - rect.left;
        const y = cursorY - rect.top;
        return {x : x, y : y};
    };

    calculatePercentage(rect, cursorX, cursorY) {
        const percentX = ((cursorX / rect.width) - 0.5).toFixed(2);
        const percentY = ((cursorY / rect.height) - 0.5).toFixed(2);
        return {x : percentX, y : percentY};
    }

    transform(percX, percY) {

        const rotationX = -percY * this.tilt;
        const rotationY = percX * this.tilt;

        this.card.style.transform = `
        perspective(${this.perspective}px) 
        rotateX(${rotationX}deg) 
        rotateY(${rotationY}deg) 
        scale(1.02)`;
    }

    reset(){
        this.card.style.transform = `rotateX(0deg) rotateY(0deg) scale(1)`;
    }
}