import {url} from './sharedWorker?sharedworker=external'
const s = (new SharedWorker(url, {type: 'module'})).port;
s.postMessage('first' + ((new URLSearchParams(location.search)).get('otp') ?? ''));
let r = 0;
let promises = new Map();
let callbacks = new Map();
export async function req(what, parameters) {
	const rr = r;
	let p = new Promise((resolve, reject) => {
		promises.set(r, [resolve, reject]);
	}).finally(() => promises.delete(rr));
	for(const property in parameters) {
		if(Array.isArray(parameters[property]) && parameters[property].every(e => e === undefined || e === null) && property !== 'terpenes') {
			parameters[property] = undefined;
		}
	}
	if(JSON.stringify(parameters) === '{}') {
		parameters = undefined;
	}
	s.postMessage(JSON.stringify({what, r, parameters}));
	++r;
	return p;
}
export function on(event, callback) {
	let e = callbacks.get(event);
	if(e === undefined) {
		e = new Set();
		callbacks.set(event, e);
		s.postMessage(`on,${event}`);
	}
	e.add(callback);
	//return this;//not chainable anymore :( but nbd?? is this the solution? https://stackoverflow.com/a/33179024/1201238
}
export function off(event, callback) {
	if(event === 'all') {
		callbacks.clear();
		s.postMessage(`off,${event}`);
	} else {
		let e = callbacks.get(event);
		let rtn = false;
		if(e === undefined) {
			console.log(`dawg ${event} event isnt even defined`)
		} else if(e.has(callback)) {
			e.delete(callback);
			rtn = true;
		} else {
			console.log(callback + ' callback does not exist under ' + event);
		}
		if(e.size === 0) {
			callbacks.delete(event);
			s.postMessage(`off,${event}`);
		}
		return rtn;
	}
}
s.onmessage = function(e) {
	if(typeof e.data === 'string') {
		console.log(e.data);
		if(e.data === 'save') {
			s.postMessage(confirm('remember me?'));
		}
	} else {
		let p = promises.get(e.data.r);
		if(p === undefined) {
			let cbs = callbacks.get(e.data.what);
			if(cbs === undefined) {
				console.log("no callbacks for " + e.data.what);
			} else {
				for(const callback of cbs) {
					callback(e.data.how, e.data.data, e.data.why);
				}
			}
		} else {
			p[Number(typeof e.data.data === 'string')](e.data.data);
		}
	}
}
addEventListener('beforeunload', function() {
	s.postMessage('closing');
});