"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Slider = void 0;
const classnames_1 = __importDefault(require("classnames"));
const react_1 = __importStar(require("react"));
const Slider_module_scss_1 = __importDefault(require("./Slider.module.scss"));
const SliderMarker = (props) => {
    var _a;
    const markerClasses = (0, classnames_1.default)(Slider_module_scss_1.default['marker'], {
        [Slider_module_scss_1.default['--fixed']]: props.fixed,
        [Slider_module_scss_1.default['--hidden']]: !((_a = props.marker) === null || _a === void 0 ? void 0 : _a.isVisible),
        [Slider_module_scss_1.default[`--${props.isEdge}`]]: !!props.isEdge,
    });
    const markerLabelClasses = (0, classnames_1.default)(Slider_module_scss_1.default['marker-label'], {
        [Slider_module_scss_1.default['--fixed']]: props.fixed,
        [Slider_module_scss_1.default[`--${props.isEdge}`]]: !!props.isEdge,
    });
    const markerStyles = {};
    if (props.offset) {
        markerStyles.left = Math.max(Math.min(100, props.offset), 0) + '%';
    }
    return (react_1.default.createElement("span", { className: markerClasses, style: markerStyles }, props.marker && !!props.marker.label && react_1.default.createElement("span", { className: markerLabelClasses }, props.marker.label)));
};
/**
 * Specifically a ranged slider, specifically for the Filter section of the Step Room display.
 * @param props
 */
const Slider = (props) => {
    var _a, _b;
    const { min = 0, max = 100 } = props;
    const [isMouseDown, setIsMouseDown] = (0, react_1.useState)(false);
    const [movingIndex, setMovingIndex] = (0, react_1.useState)(null);
    const sliderRef = (0, react_1.useRef)(null);
    const changeTrigger = (e, isOnDown = false) => {
        var _a, _b;
        const rect = (_a = sliderRef === null || sliderRef === void 0 ? void 0 : sliderRef.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
        if (!rect) {
            return;
        }
        const startX = rect.x;
        const endX = rect.x + rect.width;
        const newValue = Math.max(Math.min(Math.round(min + ((max - min) * (e.clientX - startX)) / (endX - startX)), props.max), props.min);
        let closestIndex = movingIndex;
        const markers = props.markers;
        for (let i = 0; i < markers.length; i++) {
            if (!markers[i].isVisible)
                continue;
            if (closestIndex === null || Math.abs(newValue - markers[closestIndex].value) > Math.abs(newValue - markers[i].value)) {
                closestIndex = i;
            }
        }
        const newMarkers = [...props.markers];
        if (closestIndex !== null)
            newMarkers[closestIndex].value = newValue;
        (_b = props.onChange) === null || _b === void 0 ? void 0 : _b.call(props, newMarkers);
        setMovingIndex(closestIndex);
    };
    const onMouseDown = (e) => {
        setIsMouseDown(true);
        changeTrigger(e);
    };
    const mapValueToPercent = (value) => {
        let newValue = 0;
        const totalDiff = max - min;
        const baseNewValue = value - min;
        newValue = (baseNewValue / totalDiff) * 100;
        return Math.min(Math.max(newValue, 0), 100);
    };
    (0, react_1.useEffect)(() => {
        var _a;
        let cancelled = false;
        // Creating a bounding rect here to figure out how big the slider is,
        // assumption is while the mouse is dragging, the screen size isn't going to change, right?
        // If this is wrong, add a screen size listener to check on screen size change.
        const rect = (_a = sliderRef === null || sliderRef === void 0 ? void 0 : sliderRef.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
        if (!rect) {
            return;
        }
        const startX = rect.x;
        const endX = rect.x + rect.width;
        const mouseMoveListener = (e) => {
            if (!cancelled && movingIndex !== null) {
                changeTrigger(e);
            }
        };
        const mouseUpListener = () => {
            setIsMouseDown(false);
            setMovingIndex(null);
        };
        document.body.addEventListener('mouseup', mouseUpListener);
        document.body.addEventListener('mousemove', mouseMoveListener);
        return () => {
            cancelled = true;
            document.body.removeEventListener('mouseup', mouseUpListener);
            document.body.removeEventListener('mousemove', mouseMoveListener);
        };
    }, [movingIndex]);
    return (react_1.default.createElement("div", { className: Slider_module_scss_1.default.slider, onMouseDown: onMouseDown, ref: sliderRef },
        react_1.default.createElement("div", { className: Slider_module_scss_1.default['slider-track'] }, (_b = ((_a = props.backgroundMarkers) !== null && _a !== void 0 ? _a : [])) === null || _b === void 0 ? void 0 :
            _b.map((marker, index) => {
                // TODO: Add labels if we
                // TODO: Possibly animate these with Spring library to make them smoother?
                return react_1.default.createElement(SliderMarker, { key: index, offset: mapValueToPercent(marker.value), marker: marker, fixed: true, isEdge: marker.isEdge });
            }),
            react_1.default.createElement("div", { className: Slider_module_scss_1.default['slider-rail'], style: { left: `${mapValueToPercent(props.markers[0].value)}%`, right: `${100 - mapValueToPercent(props.markers[1].value)}%` } }),
            props.markers.map((marker, index) => {
                return react_1.default.createElement(SliderMarker, { key: index, offset: mapValueToPercent(marker.value), marker: marker });
            }))));
};
exports.Slider = Slider;
//# sourceMappingURL=Slider.js.map