export const getCurrentLocation = (): Location => {
  return window.location;
};

export const getCurrentHistory = (): History => {
  return window.history;
};

export const writeLocation = (searchParams: URLSearchParams): void => {
  const location = getCurrentLocation();
  let newurl = location.protocol + '//' + location.host + location.pathname;
  if (searchParams.toString()) {
    newurl += '?' + searchParams.toString();
  }
  getCurrentHistory().replaceState({ path: newurl }, '', newurl);
};

export const handleValueInSearchParams = (
  searchParams: URLSearchParams,
  key: string,
  value: string,
): URLSearchParams => {
  if (searchParams.get(key) && !value) {
    searchParams.delete(key);
  } else if (value) {
    searchParams.set(key, value);
  }
  return searchParams;
};

export const getStringFromPathQuery = (key: string): string | null => {
  const searchParams = new URLSearchParams(getCurrentLocation().search);
  return searchParams.get(key);
};

export const getNumberFromPathQuery = (key: string): number | null => {
  const value = getStringFromPathQuery(key);
  if (value) {
    const valueAsNumber = Number(value);
    return Number.isNaN(valueAsNumber) ? null : valueAsNumber;
  }
  return null;
};

export const saveValuesToPathQuery = (
  values: { key: string; value: string }[],
): void => {
  let searchParams = new URLSearchParams(getCurrentLocation().search);
  values.forEach((val) => {
    searchParams = handleValueInSearchParams(searchParams, val.key, val.value);
  });
  writeLocation(searchParams);
};
