import React, { useRef } from 'react';
import { Wrapper, Layer } from './style';
import { IParallax, IParallaxLayer } from './types';

export const Parallax = function({ children, ...rest }: IParallax) {
    const ref: any = useRef();
    return (
        <Wrapper
            {...rest}
            ref={ref}
            onMouseMove={(e: React.MouseEvent) => {
                var x = e.clientX,
                    y = e.clientY,
                    layers = ref.current.querySelectorAll('.parallax-layer');
                for (let j = 0; j < layers.length; j++) {
                    var deep = layers[j].getAttribute('data-parallax-deep'),
                        disallow = layers[j].getAttribute('data-parallax-disallow'),
                        itemX = disallow && disallow === 'x' ? 0 : x / deep,
                        itemY = disallow && disallow === 'y' ? 0 : y / deep;
                    if (disallow && disallow === 'both') return;
                    layers[j].style.transform = 'translateX(' + itemX + '%) translateY(' + itemY + '%)';
                }
            }}
        >
            {children}
        </Wrapper>
    );
};

export const ParallaxLayer = function({ children, deep, disabledDirection, ...rest }: IParallaxLayer) {
    return (
        <Layer
            className="parallax-layer"
            data-parallax-deep={deep}
            data-parallax-disallow={disabledDirection}
            {...rest}
        >
            {children}
        </Layer>
    );
};
Parallax.Layer = ParallaxLayer;
Parallax.defaultProps = {
    height: 500,
};
export default Parallax;
