import { Inertia } from "@inertiajs/inertia";

export const getParams = () => {
    let query = window.location.search;
    query = query.replace("?", "").split("&");
    // make an object of the query string
    let queryObj = {};
    query.forEach((item) => {
        if (item !== "") {
            let key = item.split("=")[0];
            let value = item.split("=")[1];
            queryObj[key] = value;
        }
    });
    return queryObj;
};

export const addUrlParam = (param, redirect = false) => {
    let query = getParams();
    query[param.name] = param.value;

    // router.push({ path: context.route.path, query: query });
    let urlParamsString = "?";
    let i = 0;
    for (const [key, value] of Object.entries(query)) {
        i > 0 && value ? (urlParamsString += "&") : null;
        urlParamsString += value ? `${key}=${value}` : "";
        i++;
    }
    if (urlParamsString === "?") urlParamsString = "";
    const urlWithParams = window.location.pathname + urlParamsString;
    // if (Inertia.page.url !== urlWithParams)
    window.history.replaceState({}, null, urlWithParams);
    if (redirect) {
        Inertia.visit(urlWithParams);
    }
};
