import { createLogger } from "./misc/debug";

const log = createLogger("eco-stats");

type EcoStats = {
  sitesVisited: number;
  bytesEmitted: number;
  bytesSaved: number;
};

type EcoStatsDailyEntry = {
  sent: EcoStats;
  total: EcoStats;
};

type EcoStatsDailyMap = Record<string, EcoStatsDailyEntry>;

type EcoStatsChange = {
  ecoStatsDaily?: EcoStatsDailyMap;
  ecoStatsAllTime?: EcoStats;
};

const EMPTY_ECO_STATS: EcoStats = {
  sitesVisited: 0,
  bytesEmitted: 0,
  bytesSaved: 0,
};

class ExtensionPolyfill {
  private static _current: ExtensionPolyfill;

  private _api: typeof chrome | typeof browser;

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

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

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

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

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

  public async isEcoNavigationActive(): Promise<boolean> {
    const ecoNavLocal = await this._api.storage.local.get("eco-nav");
    if (ecoNavLocal == undefined) {
      return false;
    }
    return ecoNavLocal["eco-nav"];
  }

  public async getEcoStatsDaily(): Promise<EcoStatsDailyMap> {
    let result: Record<string, unknown>;
    try {
      result = await this._api.storage.local.get("ecoStatsDaily");
    } catch (error) {
      log.debug("storage.get(ecoStatsDaily) failed", error);
      throw error;
    }
    log.debug(
      "storage.get(ecoStatsDaily) raw result",
      JSON.stringify(result),
    );
    return (result?.["ecoStatsDaily"] as EcoStatsDailyMap | undefined) ?? {};
  }

  public async getEcoStatsAllTime(): Promise<EcoStats> {
    let result: Record<string, unknown>;
    try {
      result = await this._api.storage.local.get("ecoStatsAllTime");
    } catch (error) {
      log.debug("storage.get(ecoStatsAllTime) failed", error);
      throw error;
    }
    log.debug(
      "storage.get(ecoStatsAllTime) raw result",
      JSON.stringify(result),
    );
    return (result?.["ecoStatsAllTime"] as EcoStats | undefined) ?? EMPTY_ECO_STATS;
  }

  /**
   * Subscribes to live updates of the eco stats stored in browser.storage.local.
   * @returns Returns an unsubscribe function
   * @source
   */
  public onEcoStatsChanged(callback: (changes: EcoStatsChange) => void): () => void {
    const listener = (
      changes: Record<string, { newValue?: unknown }>,
      areaName: string,
    ) => {
      if (areaName !== "local") {
        return;
      }
      if (
        changes["ecoStatsDaily"] == undefined &&
        changes["ecoStatsAllTime"] == undefined
      ) {
        return;
      }
      log.debug(
        "storage.onChanged",
        JSON.stringify({
          ecoStatsDaily: changes["ecoStatsDaily"]?.newValue,
          ecoStatsAllTime: changes["ecoStatsAllTime"]?.newValue,
        }),
      );
      callback({
        ecoStatsDaily: changes["ecoStatsDaily"]?.newValue as
          | EcoStatsDailyMap
          | undefined,
        ecoStatsAllTime: changes["ecoStatsAllTime"]?.newValue as
          | EcoStats
          | undefined,
      });
    };

    (
      this._api.storage.onChanged.addListener as (cb: typeof listener) => void
    )(listener);

    return () => {
      (
        this._api.storage.onChanged.removeListener as (
          cb: typeof listener,
        ) => void
      )(listener);
    };
  }

  public async queryTab(queryInfos: (chrome.tabs.QueryInfo | browser.tabs._QueryQueryInfo)) {
    return (ExtensionPolyfill.current.tabs.query as (queryInfo: (chrome.tabs.QueryInfo | browser.tabs._QueryQueryInfo)) => Promise<(chrome.tabs.Tab | browser.tabs.Tab)[]>)(queryInfos);
  }

  public async getCurrentDomain() {
    const [tab] = await this.queryTab({
      active: true,
      currentWindow: true,
    });

    if (!tab?.url) return undefined;

    const url = new URL(tab.url);
    return url;
  }

  /**
   * Gives the language of the currently active tab's page.\
   * The `lang` (or `xml:lang`) attribute of the page's `html` tag wins, as it is the one the page scripts send to the translator API.
   * Without it, falls back to the browser's detection on the page content.
   * @returns Returns the ISO code of the page language, or undefined if it couldn't be determined
   * @source
   */
  public async detectCurrentTabLanguage(): Promise<string | undefined> {
    const [tab] = await this.queryTab({
      active: true,
      currentWindow: true,
    });

    if (tab?.id == undefined) return undefined;

    try {
      const [injection] = await (
        this._api.scripting.executeScript as (
          injection: { target: { tabId: number }; func: () => string },
        ) => Promise<{ result?: string }[]>
      )({
        target: { tabId: tab.id },
        // lang takes precedence over xml:lang (XHTML pages), as in HTML
        func: () => {
          const html = document.documentElement;
          return (html.hasAttribute("lang")
            ? html.getAttribute("lang")
            : html.getAttribute("xml:lang")) ?? "";
        },
      });
      const htmlLang = injection?.result?.trim();
      if (htmlLang) return htmlLang;
    } catch {
      // Pages where scripts can't be injected (chrome://, stores, PDFs, ...): use detection below
    }

    try {
      const language = await (
        this._api.tabs.detectLanguage as (
          tabId: number,
        ) => Promise<string>
      )(tab.id);

      return language === "und" ? undefined : language;
    } catch {
      // Some tabs (chrome://, extension pages, PDFs, not-yet-loaded pages, ...)
      // reject with "Language detection is not supported for this page."
      return undefined;
    }
  }

  public sendMessage(message: unknown) {
    //@ts-expect-error knwon
    this._api.runtime.sendMessage(this._api.runtime.id, message);
  }

  public isChrome() {
    return typeof browser == "undefined";
  }

  public async askPermissions() {
    if (this.isChrome()) {
      return true;
    }
    const response = await browser.permissions.getAll();
    const dataToAsk: browser._manifest.OptionalDataCollectionPermission[] = [];
    if (!response.data_collection?.includes("browsingActivity")) {
      dataToAsk.push("browsingActivity");
    }
    if (!response.data_collection?.includes("websiteContent")) {
      dataToAsk.push("websiteContent");
    }
    await browser.permissions.request({ data_collection: dataToAsk });
    const validation = await browser.permissions.getAll();
    return validation.data_collection?.filter(data => dataToAsk.includes(data)).length === dataToAsk.length;
  }

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

export default ExtensionPolyfill;
export type { EcoStats, EcoStatsDailyMap, EcoStatsChange };
