/*
 This file is part of GNU Taler
 (C) 2022 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

/**
 * Entry point for the background page.
 *
 * @author sebasjm
 * @author Florian Dold <dold@taler.net>
 */

/**
 * Imports.
 */
import { platform, setupPlatform } from "./platform/background.js";
import chromeAPI from "./platform/chrome.js";
import firefoxAPI from "./platform/firefox.js";
import { wxMain } from "./wxBackend.js";

const isFirefox =
  typeof (window as any) !== "undefined" &&
  typeof (window as any)["InstallTrigger"] !== "undefined";

// FIXME: create different entry point for any platform instead of
// switching in runtime
if (isFirefox) {
  setupPlatform(firefoxAPI);
} else {
  setupPlatform(chromeAPI);
}

const injectIntoTabs = async () => {
  const urlPatterns = ["https://*/*", "http://*/*"];
  const tabs = await chrome.tabs.query({ url: urlPatterns });
  for (const tab of tabs) {
    if (
      !tab.id ||
      !tab.url ||
      tab.url.startsWith("chrome://") ||
      tab.url.startsWith("edge://")
    ) {
      continue;
    }

    console.log("injecting content script into tab", tab.url);

    try {
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: ["dist/taler-wallet-interaction-loader.js"],
      });
    } catch (err) {
      // Catch errors for specific restricted pages (like Chrome Web Store)
      console.warn(`Failed to inject into tab ${tab.id}:`, err);
    }
  }
};

// Manually run content script in all tabs that are already open.
try {
  chrome.runtime.onInstalled.addListener(injectIntoTabs);
} catch (e) {
  console.error(e);
}

// Also run injection directly, in case we're in a service worker.
try {
  injectIntoTabs();
} catch (e) {
  console.error(e);
}

async function start() {
  await platform.notifyWhenAppIsReady();
  await wxMain();
}
start();
