"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.default = ImageGallerySlider;
const contexts_1 = require("../../../contexts/index.js");
const web_1 = require("@react-spring/web");
const fslightbox_react_1 = __importDefault(require("fslightbox-react"));
const react_1 = __importStar(require("react"));
const react_dom_1 = require("react-dom");
const react_use_gesture_1 = require("react-use-gesture");
const react_use_measure_1 = __importDefault(require("react-use-measure"));
const Icon_1 = __importStar(require("../../generic/Icon/Icon"));
const ImageLoader_1 = __importDefault(require("../../generic/loader/ImageLoader"));
const ImageProvider_1 = __importStar(require("../../../providers/ImageProvider"));
const Color_1 = require("../../../util/Color");
const ScreenSize_1 = __importDefault(require("../../../util/ScreenSize"));
function ImageGallerySlider(props) {
    const context = (0, react_1.useContext)(contexts_1.BookingEngineContext);
    const [{ x }, set] = (0, web_1.useSpring)(() => ({ x: 0 }));
    const [ref, bounds] = (0, react_use_measure_1.default)();
    const [prevReleasePosition, setPrevRelPos] = (0, react_1.useState)(0);
    const images = (0, react_1.useMemo)(() => {
        var _a;
        return (_a = props.images) !== null && _a !== void 0 ? _a : [];
    }, [props.images]);
    const [toggler, setToggler] = (0, react_1.useState)(false);
    const [lastReleaseX, setLastReleaseX] = (0, react_1.useState)(0);
    const [lastIndex, setLastIndex] = (0, react_1.useState)(0);
    const [isDragging, setIsDragging] = (0, react_1.useState)(false);
    let sliderVelocity = 0;
    const handleDrag = ({ down, movement: [mx], velocity }) => {
        if (context.screenSize <= ScreenSize_1.default.Medium) {
            velocity = velocity * 0.5;
            sliderVelocity = velocity > 2 ? 2 : velocity < 1 ? 1 : velocity;
        }
        else {
            sliderVelocity = 1;
        }
        const cardWidth = bounds.width;
        const maxX = images.length * cardWidth;
        if (!down) {
            const releasePosition = lastReleaseX + mx * sliderVelocity;
            let restingLocation = 0;
            let last = 0;
            if (releasePosition > 0) {
                restingLocation = 0;
                last = 0;
            }
            else if (releasePosition < -(maxX - cardWidth)) {
                restingLocation = -(maxX - cardWidth);
                last = images.length - 1;
            }
            else {
                const magic = -releasePosition / cardWidth;
                if (releasePosition >= prevReleasePosition) {
                    last = releasePosition % cardWidth > -cardWidth / 0.001 ? Math.floor(magic) : Math.ceil(magic);
                    setPrevRelPos(releasePosition + (-releasePosition % cardWidth));
                    restingLocation = -(last * cardWidth);
                }
                else {
                    last = releasePosition % cardWidth > -cardWidth / 1000 ? Math.floor(magic) : Math.ceil(magic);
                    setPrevRelPos(releasePosition - (cardWidth - (-releasePosition % cardWidth)));
                    restingLocation = -(last * cardWidth);
                }
            }
            let inPercent = 0;
            if (restingLocation !== 0) {
                inPercent = restingLocation / maxX;
            }
            setLastIndex(last);
            set({ x: inPercent });
            setLastReleaseX(restingLocation);
            setTimeout(() => {
                setIsDragging(false);
            }, 50);
        }
        else {
            let inPercent = 0;
            const newReleasePx = lastReleaseX + mx;
            inPercent = newReleasePx / maxX;
            set({ x: inPercent });
            if (mx) {
                setIsDragging(true);
            }
        }
    };
    // Set the drag hook and define component movement based on gesture data
    const bind = (0, react_use_gesture_1.useDrag)((event) => {
        handleDrag(event);
    });
    const nextImage = () => {
        handleDrag({ down: false, movement: [-bounds.width, 0], velocity: 1 });
    };
    const prevImage = () => {
        handleDrag({ down: false, movement: [bounds.width, 0], velocity: 1 });
    };
    const onClickPrevImage = () => {
        return prevImage();
    };
    const toggleToggler = () => {
        return setToggler(!toggler);
    };
    const nextImageOnClick = () => {
        return nextImage();
    };
    const toggleClickHandler = () => {
        if (!isDragging) {
            setToggler(!toggler);
        }
    };
    return (react_1.default.createElement("div", { ref: ref, className: "room-gallery-slider" },
        images.length > 1 && (react_1.default.createElement("div", { className: "room-gallery-slider__icon-left", onClick: onClickPrevImage },
            react_1.default.createElement(Icon_1.default, { icon: Icon_1.IconType.ArrowLeft2, color: Color_1.Color.White, size: "24px" }))),
        react_1.default.createElement(web_1.animated.div, Object.assign({ className: "room-gallery-slider__animation" }, bind(), { style: { left: x.to((perc) => `${perc * 100 * images.length}%`) }, onClick: toggleClickHandler }),
            react_1.default.createElement("ul", { className: "room-gallery-slider__track", style: { width: `${images.length * 100}%` } }, images.map((image, index) => {
                return (react_1.default.createElement("li", { key: `${image}-{index}`, className: "room-gallery-slider__item", style: {
                        width: `${100 / images.length}%`,
                        overflow: 'hidden',
                    } },
                    react_1.default.createElement(ImageLoader_1.default, { visible: lastIndex >= index, size: props.imageSize, draggable: false, src: image, style: { objectFit: 'cover', objectPosition: 'center', height: '100%', width: '100%' } })));
            }))),
        !!images.length && (react_1.default.createElement(react_1.default.Fragment, null,
            !props.hideLightboxIcon && (react_1.default.createElement("div", { className: "room-gallery-slider__icon-lightbox", onClick: toggleToggler },
                react_1.default.createElement(Icon_1.default, { icon: Icon_1.IconType.Fullscreen, color: Color_1.Color.White, size: "20px" }))),
            (0, react_dom_1.createPortal)(react_1.default.createElement(fslightbox_react_1.default, { toggler: toggler, sources: images.map((image) => ImageProvider_1.default.resizeImage(image, ImageProvider_1.ImageSize.Original)), type: "image", loadOnlyCurrentSource: true }), document.body))),
        images.length > 1 && (react_1.default.createElement("div", { className: "room-gallery-slider__icon-right", onClick: nextImageOnClick },
            react_1.default.createElement(Icon_1.default, { icon: Icon_1.IconType.ArrowRight2, color: Color_1.Color.White, size: "24px" })))));
}
//# sourceMappingURL=ImageGallerySlider.js.map