"use strict"

function relay(msg) {
	try {
		chrome.runtime.sendMessage(chrome.runtime.id, msg)
	} catch (ex) {}
}

function connect() {
	relay({method: 'connect'})
}
function disconnect() {
	relay({method: 'disconnect'})
}
function ping() {
	relay({method: 'ping'})
}

function onExtensionMessage(msg, sender){
	void chrome.runtime.lastError
	if (msg && sender && sender.id === chrome.runtime.id) {
		msg.external = true
		window.postMessage(msg, window.location.origin)
	}
}

function onContentMessage(msg) {
	void chrome.runtime.lastError
	if (msg && msg.data && !msg.data.external && msg.source === window) {
		relay(msg.data)
	}
}

const element = document.body || document.head || document.documentElement
const manifest = chrome.runtime.getManifest()
const rand = Date.now()

for (const res of manifest.web_accessible_resources) {
	if (!res.endsWith('.js') || res.includes('jquery')) continue
	const script = document.createElement('script')
	script.src = chrome.runtime.getURL(res)
	script.type = 'text/javascript'

	if (!element.querySelector(`script[src*='${script.src}']`)) {
		script.src += `?v=${manifest.version}&_=${rand}`
		element.appendChild(script)
	}
}

chrome.runtime.onMessage.addListener(onExtensionMessage)
window.addEventListener('message', onContentMessage)
window.addEventListener('unload', disconnect)
connect()
