import { createHashHistory } from "history";
import type { HistorySource } from "svelte-navigator";

export default function (): HistorySource {
  const history = createHashHistory({ window });
  let listeners = [];

  history.listen((location) => {
    if (history.action === "POP") {
      listeners.forEach((listener) => listener(location));
    }
  });

  return {
    get location() {
      return history.location as any;
    },
    addEventListener(name, handler) {
      if (name !== "popstate") return;
      listeners.push(handler);
    },
    removeEventListener(name, handler) {
      if (name !== "popstate") return;
      listeners = listeners.filter((fn) => fn !== handler);
    },
    history: {
      get state() {
        return history.location.state as object;
      },
      pushState(state, title, uri) {
        history.push(uri, state);
      },
      replaceState(state, title, uri) {
        history.replace(uri, state);
      },
      go(to) {
        history.go(to);
      },
    },
  };
}

export function normUrl(url: string) {
  return `/#${url.startsWith("/") ? "" : "/"}${url}`;
}
