import { Game } from './core/Game';

function showError(msg: string) {
  const ui = document.getElementById('ui')!;
  ui.innerHTML = `<div class="error"><div>${msg}</div></div>`;
}

/**
 * A world is built once, from the scenario chosen before it starts. Switching worlds used
 * to load the page again; where that is impossible (a downloaded file opened on Android
 * from a content:// address cannot be reloaded, nor can a changed address be opened) the
 * game is restarted in place instead: the old one is taken apart and a new one built in
 * the same page. Everything a game hangs on the window (event listeners, animation frames,
 * intervals, elements in the page) is tracked here per run, so it all goes with the run.
 */
let run = 0;
let abort = new AbortController();
let intervals: number[] = [];
const bodyStart = new Set(Array.from(document.body.children));

const addWin = window.addEventListener.bind(window);
const addDoc = document.addEventListener.bind(document);
const withSignal = (o?: boolean | AddEventListenerOptions): AddEventListenerOptions => (typeof o === 'object' ? { ...o, signal: o.signal ?? abort.signal } : { capture: !!o, signal: abort.signal });
window.addEventListener = ((t: string, l: EventListenerOrEventListenerObject, o?: boolean | AddEventListenerOptions) => addWin(t, l, withSignal(o))) as typeof window.addEventListener;
document.addEventListener = ((t: string, l: EventListenerOrEventListenerObject, o?: boolean | AddEventListenerOptions) => addDoc(t, l, withSignal(o))) as typeof document.addEventListener;
const raf = window.requestAnimationFrame.bind(window);
window.requestAnimationFrame = (cb: FrameRequestCallback) => {
  const mine = run;
  return raf((t) => {
    if (mine === run) cb(t);
  });
};
const setInt = window.setInterval.bind(window);
window.setInterval = ((h: TimerHandler, ms?: number, ...a: unknown[]) => {
  const id = setInt(h, ms, ...a);
  intervals.push(id);
  return id;
}) as typeof window.setInterval;

// Timers of a game that has been taken apart do not fire (their callbacks reach into it).
const setTo = window.setTimeout.bind(window);
window.setTimeout = ((h: TimerHandler, ms?: number, ...a: unknown[]) => {
  const mine = run;
  if (typeof h !== 'function') return setTo(h, ms, ...a);
  return setTo((...x: unknown[]) => {
    if (mine === run) (h as (...y: unknown[]) => void)(...x);
  }, ms, ...a);
}) as typeof window.setTimeout;

let game: Game | null = null;

function start() {
  // A fresh canvas: the old one keeps its lost context and its listeners.
  const old = document.getElementById('game') as HTMLCanvasElement;
  const canvas = old.cloneNode(false) as HTMLCanvasElement;
  old.replaceWith(canvas);
  if (!canvas.getContext('webgl2')) {
    showError('OPEN HORIZONS braucht WebGL 2. Bitte aktiviere die Hardwarebeschleunigung im Browser oder nutze einen aktuellen Browser.');
    return;
  }
  const g = new Game(canvas);
  game = g;
  g.boot().catch((e) => {
    console.error(e);
    g.ui.fatal('Die Landschaft konnte nicht erzeugt werden. Details stehen in der Browserkonsole.');
  });
}

/** Takes the running game apart and builds a new one (its choices are already in the address). */
function restart() {
  const g = game;
  run++;
  abort.abort();
  abort = new AbortController();
  for (const id of intervals) clearInterval(id);
  intervals = [];
  try {
    g?.dispose();
  } catch (e) {
    console.info('Altes Spiel nicht ganz abgebaut.', e);
  }
  game = null;
  document.getElementById('ui')!.innerHTML = '';
  for (const el of Array.from(document.body.children)) if (!bodyStart.has(el) && el.id !== 'game') el.remove();
  document.body.className = '';
  document.body.style.cursor = '';
  start();
}
(window as unknown as { __OH_RESTART: () => void }).__OH_RESTART = restart;

// The single-file build carries every asset as text in a script (about 100 MB). Once it
// has run, the asset table lives on in memory as JavaScript strings; the script's own copy
// of the text is not needed again and goes (v68).
for (const s of Array.from(document.querySelectorAll('script'))) if (!s.type && (s.textContent?.length ?? 0) > 100000) s.textContent = '';

start();
