"use strict"

const log = msg => console.log(new Date().toISOString().replace("T", " ").slice(0, -1) + ": " + msg)

globalThis.browser = globalThis.msBrowser || globalThis.browser || globalThis.chrome
globalThis.rt = globalThis.browser.runtime

function checkBackground() {
	rt.getContexts({contextTypes: ["TAB"]}, contexts => {
		if (!contexts.filter(ctx => ctx.documentUrl.endsWith("background.html")).length) {
			browser.storage.local.get('closeBG', val => !val.closeBG && browser.tabs.create({url: rt.getURL("background.html"), active: false, selected: false}))
		} else {
			setTimeout(() => rt.sendMessage(rt.id, {method: 'heartbeat'}).catch(ex => {}), 300)
		}
	})
}

browser.tabs.onRemoved.addListener((tabId, removeInfo) => {
	checkBackground()
})

rt.onMessage.addListener((msg, sender) => {
	void rt.lastError
})

rt.onInstalled.addListener(event => {
	log("Extension Installed")
	setTimeout(() => rt.sendMessage(rt.id, {method: 'install', event}).catch(ex => {}), 1e3)
})

log("Service Worker ran!")
setTimeout(checkBackground, 300)
