
$(() => {
    const INPUT_CONTAINER_CLASSES = "col-12 col-xl-3 col-md-4 col-sm-6";

    function makeDoubleSlider(minValue, maxValue, serialize) {
        if (!serialize)
            serialize = i => i;
        let resultContainer = document.createElement("div");
        resultContainer.className = `slider-container ${INPUT_CONTAINER_CLASSES}`;
        let sliderDiv = document.createElement("div");
        sliderDiv.className = "container";
        resultContainer.appendChild(sliderDiv);
        let labelRow = document.createElement("div");
        labelRow.className = "row justify-content-between";
        let minValueLabel = document.createElement("div");
        minValueLabel.className = "slider-value slider-min-value";
        minValueLabel.textContent = serialize(minValue);
        labelRow.appendChild(minValueLabel);
        let maxValueLabel = document.createElement("div");
        maxValueLabel.className = "slider-value slider-max-value";
        maxValueLabel.textContent = serialize(maxValue);
        labelRow.appendChild(maxValueLabel);
        sliderDiv.appendChild(labelRow);
        let inputContainer = document.createElement("div");
        inputContainer.className = "container";
        sliderDiv.appendChild(inputContainer);
        let sliderCol = document.createElement("div");
        sliderCol.className = "col slider-col";
        inputContainer.appendChild(sliderCol);
        let input = document.createElement("input");
        input.type = "text";
        input.className = "col";
        input.dataset.sliderMin = minValue ?? 0;
        input.dataset.sliderMax = maxValue ?? 100;
        input.dataset.sliderValue = `[${input.dataset.sliderMin},${input.dataset.sliderMax}]`;
        input.dataset.sliderTooltip = "hide";
        sliderCol.appendChild(input);
        let jQueryInput = $(input);
        jQueryInput.slider();
        let onChange = () => {};
        jQueryInput.on('slideStop', evt => onChange({ min: evt.value[0], max: evt.value[1] }));
        jQueryInput.on('slide', evt => {
            minValueLabel.textContent = serialize(evt.value[0]);
            maxValueLabel.textContent = serialize(evt.value[1]);
        });
        return {
            container: resultContainer,
            minValueLabel: minValueLabel,
            maxValueLabel: maxValueLabel,
            input: jQueryInput,
            getInputValue: () => { const val = jQueryInput.slider('getValue'); return { min: val[0], max: val[1] }; },
            onChange: (fnc) => { onChange = fnc; }
        };
    }

    window.ReloadFilters = function(mediaManager) {
        let buildFilterBar = (labelText, canBeEmpty, possibleValues) => {
            let result = document.createElement("div");
            result.className = INPUT_CONTAINER_CLASSES;
            let label = document.createElement('label');
            result.appendChild(label);
            label.textContent = labelText;
            label.className = "container";
            let select = document.createElement('select');
            select.multiple = 'multiple';
            label.appendChild(select);
            for (let i of [].concat(canBeEmpty ? [undefined] : [], possibleValues)) {
                let opt = document.createElement("option");
                opt.textContent = i ? i : "(Empty)";
                opt.value = i ?? "";
                select.appendChild(opt);
            }
            $(select).change(e => {
                let val = Array.from(select.children).filter(i => i.selected).map(i => i.value === '' ? undefined : i.value);
                window.FilterManager.setFilterValue(labelText, val);
            });
            $(select).bsMultiSelect({cssPatch: {
                picks: { backgroundColor: 'inherit' },
                pick: { color: 'var(--bs-body-color)' },
                choiceContent: { color: 'var(--bs-body-color)' }
            }});
            return {
                content: result
            };
        };

        let container = document.getElementById('pch-filterbar');
        container.textContent = '';
        if (MediaStorage.Instance.isLoading())
            return;
        for (let i of Object.keys(mediaManager.allMetaTypes).filter(i => mediaManager.allMetaTypes[i].type === 'string' ||
                [].indexOf(i) >= 0)) {
            let filterUi = buildFilterBar(i, mediaManager.allMetaTypes[i].canBeEmpty, Array.from(mediaManager.allMeta[i]).sort());
            container.appendChild(filterUi.content);
        }

        let filterUi = buildFilterBar("Tags", true, Array.from(mediaManager.allTags).sort());
        container.appendChild(filterUi.content);

        if (window.chronology.isInitialized()) {
            let range = window.chronology.getRange();
            let timeSlider = makeDoubleSlider(range.min.getTime(), range.max.getTime(), i => (new Date(i)).toLocaleDateString());
            timeSlider.onChange(val => window.FilterManager.setChronologyRange(val.min, val.max));
            container.appendChild(timeSlider.container);
        }
    }

    document.getElementById('pch-navbar-filterToggle').addEventListener('click', e => {
        e.preventDefault();
        let filterBarDom = document.getElementById('pch-filterbarContainer');
        if (filterBarDom.style.display)
            filterBarDom.style.display = "";
        else
            filterBarDom.style.display = "flex"
    });

    document.onClosePopinRequested(() => {
        document.getElementById('pch-filterbarContainer').style.display = "";
    });
});

