"use strict"

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

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

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

chrome.runtime.onInstalled.addListener(event => {
	console.log(`${new Date().toISOString().replace("T", " ").slice(0, -1)} Extension Installed`)
	setTimeout(() => chrome.runtime.sendMessage(null, {method: 'install', event}).catch(ex => {}), 1e3)
})

console.log(`${new Date().toISOString().replace("T", " ").slice(0, -1)} Service Worker ran!`)
setTimeout(checkBackground, 300)
