import { createPath } from "@remix-run/router";

import { To } from "react-router";
import { IHistoryContext } from "redux-first-history";

export function invariant(value: boolean, message?: string): asserts value;
export function invariant<T>(
  value: T | null | undefined,
  message?: string,
): asserts value is T;
export function invariant(value: any, message?: string) {
  if (value === false || value === null || typeof value === "undefined") {
    throw new Error(message);
  }
}

function createURL(to: To): URL {
  // window.location.origin is "null" (the literal string value) in Firefox
  // under certain conditions, notably when serving from a local HTML file
  // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
  let base =
    window.location.origin !== "null"
      ? window.location.origin
      : window.location.href;

  let href = typeof to === "string" ? to : createPath(to);
  invariant(
    base,
    `No window.location.(origin|href) available to create URL for href: ${href}`,
  );
  return new URL(href, base);
}

function encodeLocation(to: To) {
  // Encode a Location the same way window.location would
  let url = createURL(to);
  return {
    pathname: url.pathname,
    search: url.search,
    hash: url.hash,
  };
}

type HF = IHistoryContext["createReduxHistory"];
export type ReduxNavtionHistory = ReturnType<HF>;

const wrapHistory = (history: ReduxNavtionHistory): ReduxNavtionHistory => {
  const newHistory: ReduxNavtionHistory = Object.assign({
    ...history,
    encodeLocation,
    createURL,
  });
  return newHistory;
};

export default wrapHistory;