import React, { useEffect, useRef } from "react";
import { hsvToHex } from "../../../utils/colorConvectors/hsvToHex";
import { calculateChange } from "./helpers/calculateChange";
import { Saturation, PointButton, SaturationActiveBlock } from "./styles";
var SaturationBlock = function (_a) {
    var hsv = _a.hsv, hsl = _a.hsl, setHsv = _a.setHsv, setColorInput = _a.setColorInput;
    var container = useRef(null);
    useEffect(function () { return function () { return unbindEventListeners(); }; }, []);
    var handleChange = function (e) {
        if (container.current) {
            var change = calculateChange(e, hsl, container.current);
            setHsv(change);
            setColorInput(hsvToHex(change).toUpperCase());
        }
    };
    var handleMouseUp = function () {
        unbindEventListeners();
    };
    var handleMouseDown = function (e) {
        handleChange(e);
        var renderWindow = getContainerRenderWindow();
        if (renderWindow) {
            renderWindow.addEventListener("mousemove", handleChange);
            renderWindow.addEventListener("mouseup", handleMouseUp);
        }
    };
    var unbindEventListeners = function () {
        var renderWindow = getContainerRenderWindow();
        if (renderWindow) {
            renderWindow.removeEventListener("mousemove", handleChange);
            renderWindow.removeEventListener("mouseup", handleMouseUp);
        }
    };
    var getContainerRenderWindow = function () {
        var currentContainer = container === null || container === void 0 ? void 0 : container.current;
        var renderWindow = window;
        while (!renderWindow.document.contains(currentContainer) &&
            renderWindow.parent !== renderWindow) {
            renderWindow = renderWindow.parent;
        }
        return renderWindow;
    };
    return (React.createElement(Saturation, { ref: container, onMouseDown: handleMouseDown, onTouchMove: handleChange, onTouchStart: handleChange, hue: hsl.h },
        React.createElement(SaturationActiveBlock, { ref: container },
            React.createElement(PointButton, { top: Number(String(hsv.v).substr(0, 4)), left: Number(String(hsv.s).substr(0, 4)), hex: hsvToHex(hsv) }))));
};
export default SaturationBlock;
