import { flatMap } from "lodash"
import browser from "webextension-polyfill"
import { query } from "./graphql/api"
import { updateTabIcons } from "./update"

function replaceFiles({ tabId, frameId }: { tabId: number; frameId: number }) {
  void browser.tabs.sendMessage(tabId, { method: "fileUpdated" }, { frameId })
}

browser.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
  const { method, body } = msg
  if (method === "gql") {
    query(body.query, body.variables)
      .then(result => {
        if (process.env.NODE_ENV === "development") {
          console.log({ ...body, result })
        }
        // @ts-expect-error wrong type
        sendResponse(result)
      })
      .catch(console.error)
    return true
  }
})

browser.webNavigation.onCommitted.addListener(updateTabIcons)
browser.webNavigation.onHistoryStateUpdated.addListener(info => {
  void updateTabIcons(info)
  replaceFiles(info)
})
browser.webNavigation.onBeforeNavigate.addListener(updateTabIcons)

browser.tabs.onUpdated.addListener((tabId, info) => {
  void updateTabIcons({ ...info, tabId, url: info.url, frameId: 0 })
  if (info.status === "loading") {
    replaceFiles({ tabId, frameId: 0 })
  }
})

const tabs = flatMap(
  await browser.windows.getAll({ populate: true }),
  window => window.tabs!,
)

await Promise.all(
  tabs.map(tab => updateTabIcons({ tabId: tab.id!, url: tab.url, frameId: 0 })),
)
