import {Config} from "./Config.js";
import {LGT} from "./Util.js";
import {UtilApplications} from "./UtilApplications.js";

class RivetBridge {
	static init () {
		window.addEventListener("rivet.receive", evt => {
			console.log(...LGT, `Received Rivet message (JSON)`);
			return this._handlePacket(evt.detail);
		});

		window.addEventListener("rivet.receive-text", () => {
			console.log(...LGT, `Received Rivet message (text)`);
			const $ipts = $(`textarea.rivet-transfer`);
			const packetRaw = $ipts.last().val();
			$ipts.remove();
			return this._handlePacket(JSON.parse(packetRaw));
		});
	}

	static _handlePacket (pack) {
		switch (pack.type) {
			case "roll": return this._handleRollMessage(pack);
			case "entity": return this._pHandleEntityMessage(pack);
			default: ui.notifications.error(`Unhandled Rivet message with type "${pack.type}"! You may need to update your extension.`);
		}
	}

	static _handleRollMessage (pack) {
		const data = pack.data;

		if (!pack.settings.isSendRolls) return;

		const roll = new Roll(data.dice);

		const whisper = [];
		if (pack.settings.isWhisper) whisper.push(game.userId);

		roll.toMessage({
			speaker: {
				alias: data.rolledBy,
			},
			flavor: data.label,
			rollMode: "roll",
			whisper,
		});
	}

	/** Import an entity. */
	static async _pHandleEntityMessage (pack) {
		const minRole = Config.get("import", "minimumRole");
		if (game.user.role < minRole) return;

		const data = pack.data;

		const targetActorId = (Config.get("rivet", "targetActorId") || "").trim();
		const actor = targetActorId ? CONFIG.Actor.collection.instance.get(targetActorId) : "";

		const {ChooseImporter} = await import("./ChooseImporter.js");
		const importer = ChooseImporter.getImporter(data?.entity?.__prop || data.page, actor);
		if (!importer) return ui.notifications.error(`Plutonium does not yet support entities from "${data.page}"! You may need to update your extension.`);
		try {
			await importer.pInit();
			const opts = {};
			if (data.isTemp) opts.isTemp = true;
			const importedMeta = await importer.pImportEntry(data.entity, opts);
			UtilApplications.doShowImportedNotification(importedMeta);
		} catch (e) {
			UtilApplications.doShowImportedNotification({entity: data, status: UtilApplications.TASK_EXIT_FAILED});
			setTimeout(() => { throw e; });
		}
	}
}

export {RivetBridge};
