/**
 * Set URL
 *
 * @param currentPath
 * @param pagerStatus
 */
function setUrlSearchParams(currentPath, pagerStatus) {
    if(currentPath && !pagerStatus) {
        let baseUrlWithSearchParam = window.location.href.split('&')[0];
        currentPath = currentPath.split('&');

        currentPath.forEach((urlParam) => {
            if(urlParam) {
                if(!urlParam.includes('page')){
                    baseUrlWithSearchParam +=  `&${urlParam}`;
                }
            }
        });

        window.history.pushState("", "", baseUrlWithSearchParam);
    } else if(currentPath && pagerStatus) {
        let baseUrlWithSearchParam = window.location.href.split('&')[0];
        currentPath = currentPath.split('&');

        currentPath.forEach((urlParam) => {
            if (urlParam) {
                baseUrlWithSearchParam += `&${urlParam}`;
            }
        });

        window.history.pushState("", "", baseUrlWithSearchParam);
    }
}

/**
 * Transform Category URL
 * from / to &
 *
 * @param url
 * @returns {*}
 */
function transformCategoryUrl(url) {
    let modifiedUrl = url.replace(/\//g, '&').replace(/:/g, '=').replace(/,/g, '_')

    //Removing filter undefined from url
    if(modifiedUrl.includes('&filter=undefined')) {
        modifiedUrl = modifiedUrl.split('&filter=undefined');
        modifiedUrl = modifiedUrl.join('');
    }

    return modifiedUrl.replace(/&$/, '');
}

/**
 * Transform category params for url
 *
 * @return {string}
 */
function transformCategoryParams()
{
    let categoryParams = '';

    const categoryElements = JSON.parse(localStorage.getItem('category'));
    Object.entries(categoryElements).forEach((categoryElement) => {
        const key = categoryElement[0];
        const value = categoryElement[1];

        if(key === 'category') {
            categoryParams += `?${key}=${value}`;
        } else {
            categoryParams += `&${key}=${value}`;
        }
    });

    return categoryParams;
}


/**
 * Set Url Category Params
 *
 * @param currentPath
 */
function setUrlCategoryParams(currentPath) {
    const baseUrl = window.location.href.split('?')[0];
    const categoryParams = transformCategoryParams();

    let searchParams = '';

    currentPath = currentPath.split('&');

    currentPath.forEach((urlParam) =>
        urlParam ?
            searchParams += `${transformCategoryUrl(urlParam)}` :
            null
    );

    window.history.pushState("", "", `${baseUrl}${categoryParams}${searchParams}`);
}

export {
    setUrlSearchParams,
    setUrlCategoryParams
}