function UrlUtils() {
  function getUrl() {
    return window.location.href;
  }

  function setUrl(url) {
    history.pushState(null, null, url);
  }

  function addQueryParameter(url, key, value) {
    let [baseUrl, queryString] = url.split("?");
    let queryParameters = queryString ? queryString.split("&") : [];

    let hasKey = false;
    for (let i = 0; i < queryParameters.length; i++) {
      const [paramKey] = queryParameters[i].split("=");
      if (paramKey === key) {
        queryParameters[i] = `${key}=${value}`;
        hasKey = true;
        break;
      }
    }

    if (!hasKey) {
      queryParameters.push(`${key}=${value}`);
    }

    const newUrl = `${baseUrl}?${queryParameters.join("&")}`;
    return newUrl;
  }

  function removeQueryParameter(url, key) {
    let [baseUrl, queryString] = url.split("?");
    let queryParameters = queryString ? queryString.split("&") : [];

    for (let i = 0; i < queryParameters.length; i++) {
      const [paramKey] = queryParameters[i].split("=");
      if (paramKey === key) {
        queryParameters.splice(i, 1);
        break;
      }
    }

    const newUrl = `${baseUrl}?${queryParameters.join("&")}`;
    return newUrl;
  }

  function getQueryParameter(key) {
    let url = getUrl();
    let [baseUrl, queryString] = url.split("?");
    let queryParameters = queryString ? queryString.split("&") : [];

    for (let i = 0; i < queryParameters.length; i++) {
      const [paramKey, paramValue] = queryParameters[i].split("=");
      if (paramKey === key) {
        return decodeURIComponent(paramValue);
      }
    }

    return null;
  }

  return {
    addQueryParameter,
    removeQueryParameter,
    getQueryParameter,
    getUrl,
    setUrl,
  };
}

UrlUtils = new UrlUtils();

export default UrlUtils;
