import browser from "webextension-polyfill"
import type { BackgroundQueryDocument } from "~/generated/graphql"
import { queryOrThrow } from "./graphql/api"

const gql = String.raw

const BACKGROUND_QUERY = gql`
  query BackgroundQuery($url: String!) {
    preferences {
      enabled
    }
    files(filter: { url: $url, enabled: true }) {
      id
    }
  }
`

export async function updateTabIcons({
  frameId,
  tabId,
  url,
  status,
}: {
  frameId?: number
  tabId: number
  url?: string
  status?: string
}) {
  if (
    !url ||
    url.startsWith("chrome-error://") ||
    url.startsWith("chrome-extension://") ||
    url.startsWith("chrome://newtab/")
  ) {
    return
  }

  const {
    preferences: { enabled },
    files,
  } = await queryOrThrow<BackgroundQueryDocument>(BACKGROUND_QUERY, { url })

  await browser.browserAction.setBadgeBackgroundColor({
    color: enabled ? [251, 43, 105, 255] : [170, 170, 170, 255],
  })

  if (frameId && frameId !== 0) {
    return
  }

  const count = files.length

  try {
    if (url === "chrome://newtab/" && status && status !== "complete") return

    if (!(await tabExists(tabId))) return

    const postfix = enabled ? "" : "w"

    await browser.browserAction.setIcon({
      tabId,
      path: {
        16: `assets/images/16${postfix}.png`,
        32: `assets/images/32${postfix}.png`,
        19: `assets/images/19${postfix}.png`,
        38: `assets/images/38${postfix}.png`,
      },
    })

    if (count) {
      await browser.browserAction.setBadgeText({
        text: `${count}`,
        tabId,
      })
    }
  } catch {}
}

async function tabExists(id?: number) {
  try {
    return Boolean(id != null && (await browser.tabs.get(id)))
  } catch {
    return false
  }
}
