/**
 * Fenêtre de la page lue, passée dans l'URL d'un lecteur ouvert dans sa
 * propre fenêtre (`reading-mode.html?window=<id>`).
 * @returns L'identifiant de la fenêtre, `undefined` dans un panneau latéral
 */
export function getReaderWindowParam(): number | undefined {
  const param = new URLSearchParams(window.location.search).get("window");
  const windowId = param == undefined || param === "" ? NaN : Number(param);
  return Number.isInteger(windowId) ? windowId : undefined;
}

class ExtensionPolyfill {
  private static _current: ExtensionPolyfill;

  private _api: typeof chrome | typeof browser;

  public get runtime() {
    return this._api.runtime;
  }

  public get tabs() {
    return this._api.tabs;
  }

  /**
   * Fenêtre du document courant (le panneau latéral compris), `undefined` si
   * l'API n'est pas disponible dans ce contexte (script de contenu).
   */
  public async getCurrentWindowId(): Promise<number | undefined> {
    try {
      const windows = this._api.windows as typeof browser.windows | undefined;
      return (await windows?.getCurrent())?.id;
    } catch {
      return undefined;
    }
  }

  /**
   * Fenêtre de la page lue par ce lecteur. Un lecteur ouvert dans sa propre
   * fenêtre la reçoit dans son URL (`reading-mode.html?window=<id>`) ; un
   * panneau latéral est dans la fenêtre de la page.
   */
  public async getReaderSourceWindowId(): Promise<number | undefined> {
    const sourceWindowId = getReaderWindowParam();
    return sourceWindowId ?? (await this.getCurrentWindowId());
  }

  /**
   * Le port d'un lecteur (panneau latéral ou fenêtre) n'a pas d'onglet de la
   * page : le background ne sait pas de quelle fenêtre il dépend. Le lecteur
   * la lui envoie dans un second `open_channel`, y compris après chaque
   * reconnexion (redémarrage du service worker).
   * @param port - Port du lecteur vers le background
   * @param message - Message de l'`open_channel`
   */
  public sendReaderWindow(
    port: { postMessage: (message: object) => void },
    message: string,
  ) {
    void this.getReaderSourceWindowId().then((windowId) => {
      if (windowId == undefined) {
        return;
      }
      try {
        port.postMessage({
          name: "open_channel",
          datas: JSON.stringify({ message, windowId }),
        });
      } catch {
        // Port déjà fermé : la reconnexion renverra la fenêtre.
      }
    });
  }

  public static get current() {
    if (this._current == undefined) {
      this._current = new ExtensionPolyfill();
    }
    return this._current;
  }

  constructor() {
    if (typeof browser == "undefined") {
      this._api = chrome;
    } else {
      this._api = browser;
    }
  }
}

export default ExtensionPolyfill;
