import { check } from "prettier";

(function ($) {
	const getQueryVar = function (parameter) {
		var url = window.location.href;
		var searchParams = new URLSearchParams(new URL(url).search);
		var queryVarValue = searchParams.get(parameter);
		return queryVarValue;
	};

	const addQueryVar = function (parameter, value) {
		var url = window.location.href;
		var urlObj = new URL(url);
		var searchParams = urlObj.searchParams;
		searchParams.set(parameter, value);
		urlObj.search = searchParams.toString();
		var modifiedUrl = urlObj.toString();
		window.history.replaceState(null, '', decodeURIComponent(modifiedUrl));
	};

    const  ltrim = function(str, chr) {
        var rgxtrim = (!chr) ? new RegExp('^\\s+') : new RegExp('^'+chr+'+');
        return str.replace(rgxtrim, '');
      }

	const removeQueryVar = function (parameter) {
		var url = window.location.href;
		var urlObj = new URL(url);
		var searchParams = urlObj.searchParams;
		searchParams.delete(parameter);
		urlObj.search = searchParams.toString();
		var modifiedUrl = urlObj.toString();
		window.history.replaceState(null, '', decodeURIComponent(modifiedUrl));
	};

	const uniqueArray = function (array) {
		return array.filter(function (item, pos) {
			return array.indexOf(item) == pos;
		});
	};

	const filterAttributes = function (event) {
		let checkedBoxes = $('.wcv_block-store-attributes-filter__attribute-checkbox:checked');
		let filterAttrs =[];
        $.map(checkedBoxes, function (checkbox) {
            if (filterAttrs[checkbox.name] === undefined) {
               return filterAttrs[checkbox.name] = checkbox.value;
            } else {
                return filterAttrs[checkbox.name] = ltrim(filterAttrs[checkbox.name] + ',' + checkbox.value, ',');
            }   
        });

        let filterTypes = '';
        for (let [key, value] of Object.entries(filterAttrs)) {
            filterTypes += key+',';
            addQueryVar(`filter_${key}`, value);
        }
        filterTypes = ltrim(filterTypes, ',');
        addQueryVar('filter_attribute', filterTypes);
        window.location.reload();
    }

	$(document).ready(function () {
		$('.wcv_block-store-attributes-filter__attribute-checkbox').on('click', filterAttributes);
	});
})(jQuery);

