let run_price_events = true;

$(document).ready(function () {
    let priceSlider = document.querySelector('.filter-price-box .filter-price-slider'),
        minBox = document.querySelector('.filter-price__min-value'),
        maxBox = document.querySelector('.filter-price__max-value'),
        inputs = [
            minBox.querySelector('input'),
            maxBox.querySelector('input')
         ],
        formattedInputs = [
            minBox.querySelector('.filter-price__formatted'),
            maxBox.querySelector('.filter-price__formatted')
        ],
        priceFormat = wNumb({
            mark: '.',
            thousand: ',',
            prefix: $("#current_currency_symb").val(),
        });

    initPriceSlider(priceSlider);

    priceSlider.noUiSlider.on('update', function (values, handle) {
        inputs[handle].value = parseInt(values[handle]);
        formattedInputs[handle].innerHTML = priceFormat.to(parseInt(values[handle])); 
    });

    priceSlider.noUiSlider.on('set', function (values, handle) {
        inputs[handle].value = parseInt(values[handle]);
        
        formattedInputs[handle].innerHTML = priceFormat.to(parseInt(values[handle]));
 
        // console.log('Slider set', values);

        if ( $('#filter-modal').hasClass('show') ) {
            filterProductsByPrice(values);
        }        
    });


    inputs.forEach(function (input, handle) {
        input.addEventListener('blur', function () { 
            priceSlider.noUiSlider.setHandle(handle, this.value);
 
            console.log('Slider blur', this.value);
 
            filterProductsByPrice( priceSlider.noUiSlider.get() );                        
        });
    });

    //TODO: activate this events when the popular section will be activated
    /*ranges.forEach(function (el) {
        el.addEventListener('click', function () {
            const minRange = el.getAttribute('data-min') ? el.getAttribute('data-min') : min,
                  maxRange = el.getAttribute('data-max') ? el.getAttribute('data-max') : max;

            console.log('DDD');

            priceSlider.noUiSlider.set([minRange, maxRange]);
        });
    });*/ 

    
});

function initPriceSlider (priceSlider, min = 0, max = 1) {
  
    noUiSlider.create(priceSlider, {
        start: [min, max],
        range: {min: min, max: max},
        connect: true,
        pips: {
            mode: 'count',
            values: 5,
            format: wNumb({
                thousand: ',',
                prefix: $("#current_currency_symb").val()
            })
        },
    });
} 


async function setPriceRange(price_range)
{
    let priceSlider = document.querySelector('.filter-price-box .filter-price-slider'),
        ranges = getPriceRangesByMinMaxPrices(price_range);

    price_range.selected_min_price = await convertPriceToCurrentCurrency(price_range.selected_min_price);
    price_range.selected_max_price = await convertPriceToCurrentCurrency(price_range.selected_max_price);
 
    priceSlider.noUiSlider.updateOptions({
        range: ranges,
        start: [
            price_range.selected_min_price,
            price_range.selected_max_price
        ]
    });
}

function getPriceRangesByMinMaxPrices(price_range)
{
    let min = convertPriceToCurrentCurrency(parseInt(price_range.min)),
        max = convertPriceToCurrentCurrency(parseInt(price_range.max));

    return {
        'min': [    min ],
        '25%': [  parseInt(max * 0.25) ],
        '50%': [  parseInt(max * 0.5) ],
        '75%': [  parseInt(max * 0.75) ],
        'max': [    max ]
    };
}

function convertPriceToCurrentCurrency(price)
{
    let rate = parseFloat(woocs_current_currency.rate);

    return parseInt(price * rate);
}
 
function isFilterShowing()
{
    return $("#filter-modal").hasClass('show');
}


function filterProductsByPrice(price_range)
{
    let url_query = window.location.search,
        pathname = window.location.pathname,
        urlParams = new URLSearchParams(url_query);

    //Update ranges to url 
    urlParams.delete('f_prices');

    changeUrl(pathname + '?' + urlParams.toString() + '&f_prices=' + parseInt(price_range[0]) + '_' + parseInt(price_range[1]));  

    $(".filter-modal__tabs-list li[data-name='price']").trigger('click', {action: 'filterReload'});
}

function initMobPriceSlider(selected_min, selected_max) {
    let mobPriceBox = document.querySelector('.filter-modal__tabs-item[data-name=price] .filter-price__body'),
        mobPriceBoxValues = document.querySelector('.filter-price__mob'),
        tagPriceSlider = mobPriceBox.querySelector('.filter-price-slider'),
        minValue = mobPriceBoxValues.getAttribute('min'),
        maxValue = mobPriceBoxValues.getAttribute('max'),
        selectedMinValue = selected_min,
        selectedMaxValue = selected_max,
        minBox = mobPriceBox.querySelector('.filter-price__min-value'),
        maxBox = mobPriceBox.querySelector('.filter-price__max-value'),
        inputs = [
            minBox.querySelector('input'),
            maxBox.querySelector('input')
        ],
        formattedInputs = [
            minBox.querySelector('.filter-price__formatted'),
            maxBox.querySelector('.filter-price__formatted')
        ],
        priceFormat = wNumb({
            mark: '.',
            thousand: ',',
            prefix: $("#current_currency_symb").val(),
        });

    selectedMinValue = convertPriceToCurrentCurrency(+selectedMinValue);
    selectedMaxValue = convertPriceToCurrentCurrency(+selectedMaxValue);

    minValue = convertPriceToCurrentCurrency(parseInt(minValue));
    maxValue = convertPriceToCurrentCurrency(parseInt(maxValue));

    noUiSlider.create(tagPriceSlider, {
        range: {
            'min': [    minValue ],
            '25%': [    parseInt(maxValue * 0.25) ],
            '50%': [    parseInt(maxValue * 0.5) ],
            '75%': [    parseInt(maxValue * 0.75) ],
            'max': [    maxValue ]
        },
        start: [
            selectedMinValue,
            selectedMaxValue
        ],
        connect: true,
        pips: {
            mode: 'count',
            values: 5,
            format: wNumb({
                thousand: ',',
                prefix: $("#current_currency_symb").val()
            })
        },
    });

    tagPriceSlider.noUiSlider.on('update', function (values, handle) {
        inputs[handle].value = parseInt(values[handle]);
        formattedInputs[handle].innerHTML = priceFormat.to(parseInt(values[handle]));
    });

    tagPriceSlider.noUiSlider.on('set', function (values, handle) {
        inputs[handle].value = parseInt(values[handle]);

        formattedInputs[handle].innerHTML = priceFormat.to(parseInt(values[handle]));

        filterProductsByPrice( values );
    });

    inputs.forEach(function (input, handle) {
        input.addEventListener('blur', function () {
            tagPriceSlider.noUiSlider.setHandle(handle, this.value);

            console.log('Mob slider blur', this.value);

            filterProductsByPrice( tagPriceSlider.noUiSlider.get() );
        });
    });
}