import { OmRangeSlider } from '../../../global/om-range-slider/om-range-slider.js';
import { changePrice } from './change-price.js';

/**
 * Check if should enable Request for Price Range
 *
 * @param enableRequest
 * @param priceFrom
 * @param priceTo
 * @return {boolean}
 */
function shouldEnableRequest(
    enableRequest,
    priceFrom,
    priceTo
) {
    if(enableRequest) {
        priceFrom = parseFloat(priceFrom).toFixed(2);
        priceTo = parseFloat(priceTo).toFixed(2);

        if(!isNaN(priceFrom) || !isNaN(priceTo)) {
            changePrice(priceFrom, priceTo);
            enableRequest = false;
        }
    }

    return enableRequest;
}

/**
 * Price Range
 */
function handlePriceRange() {
    OmRangeSlider.init();

    const priceRange = document.querySelector('#price-range-slider');
    if(priceRange) {
        const startButton = document.querySelector('.om-sliderrange-button-start');
        const endButton = document.querySelector('.om-sliderrange-button-end');

        let priceFrom = '';
        let priceTo = '';

        let enableRequest = false;

        document.addEventListener('rangechange', event => {
            priceFrom = event.detail[0];
            priceTo = event.detail[1];
        });

        startButton?.addEventListener('mousedown', () => {
            enableRequest = true;
        });

        startButton?.addEventListener('touchstart', () => {
            enableRequest = true;
        }, { passive: true });

        endButton?.addEventListener('mousedown', () => {
            enableRequest = true;
        });

        endButton?.addEventListener('touchstart', () => {
            enableRequest = true;
        }, { passive: true });

        window.addEventListener('mouseup', () => {
            enableRequest = shouldEnableRequest(
                enableRequest,
                priceFrom,
                priceTo
            );
        });

        window.addEventListener('touchend', () => {
            enableRequest = shouldEnableRequest(
                enableRequest,
                priceFrom,
                priceTo
            );
        }, { passive: true });
    }
}

export {
    handlePriceRange
}