//LiteLoaderScript Dev Helper
/// <reference path="c:\Users\Administrator\.vscode\extensions\moxicat.llscripthelper-2.1.5/dts/llaids/src/index.d.ts"/> 

ll.registerPlugin(
	"CMENU.js",
	"自定义菜单",
	[0, 2, 5],
	{
		"Author": "提米吖"
	}
);

Array.prototype.forEach = function (cb) {
	let l = this.length, i = 0;
	while (i < l) {
		cb(this[i], i, this);
		i++;
	}
}

let cache = new Map();

function ST(pl, text) {
	pl.tell(`§l§d[CMENU] ${text}`, 0);
}

/**
 * 
 * @param {Player} pl 
 * @param {string} fileName 
 */
function SendMenuForm(pl, fileName) {
	let xuid = pl.xuid;
	if (!xuid) { return; }
	pl.tell('开始读取文件' + fileName + '.json', 5);
	let e = new File(`./plugins/CMENU/${fileName}.json`, File.ReadMode, false);
	e.readAll((res) => {
		let pl = mc.getPlayer(xuid);
		if (pl == null) { return; }
		if (res == null) {
			ST(pl, `§c文件读取失败!`);
			return;
		}
		try {
			let arr = JSON.parse(res);
			if (Object.prototype.toString.call(arr) != "[object Array]") { log("T"); throw new Error(""); }
			let nf = mc.newSimpleForm();
			nf.setTitle("§l§dCMENU");
			nf.setContent("菜单如下:");
			arr.forEach((obj) => {
				nf.addButton(obj.name, (obj.image || ""));
			});
			pl.sendForm(nf, (pl, id) => {
				if (id == null) { ST(pl, "§b表单已放弃"); return; }
				let sel = arr[id];
				switch (sel.type) {
					case "comm": {
						pl.runcmd(sel.open);
						break;
					}
					case "opcomm": {
						if (pl.permLevel != 0) {
							pl.runcmd(sel.open);
						} else {
							ST(pl, '§c你没有权限使用这个命令');
						}
						break;
					}
					case "form": {
						SendMenuForm(pl, sel.open);
						break;
					}
					case "opform": {
						if (pl.permLevel != 0) {
							SendMenuForm(pl, sel.open);
						} else {
							ST(pl, '§c你没有权限打开这个子菜单');
						}
						break;
					}
					default: {
						ST(pl, 'type参数错误！');
						logger.error('文件："' + fileName + '.json" name: "' + sel.name + '" type参数错误!');
						break;
					}
				}
			});
		} catch (e) {
			ST(pl, `§c菜单配置错误!`);
			logger.error("无法解析表单: ", fileName, ".json");
		}
		e.close();
	});
}

//祖传屎山就不要乱动拉(QWQ)
function start() {
	let json = File.exists('.\\plugins\\CMENU\\main.json');
	if (!json) {
		File.createDir('.\\plugins\\CMENU');
		let xie = [{ "name": "noOpTest", "image": "https://z3.ax1x.com/2021/07/18/W31CBd.jpg", "open": "/me test", "type": "comm" }, { "name": "opTest", "image": "https://z3.ax1x.com/2021/07/18/W31CBd.jpg", "open": "/me hello world", "type": "opcomm" }, { "name": "noOpTestForm", "image": "https://z3.ax1x.com/2021/07/18/W31CBd.jpg", "open": "hhh", "type": "form" }, { "name": "opTestForm", "open": "ooo", "type": "opform" }];
		let Json = JSON.stringify(xie, null, "\t");
		File.writeTo('.\\plugins\\CMENU\\main.json', Json);
		let xi = [{ "name": "opTest", "image": "https://z3.ax1x.com/2021/07/18/W31CBd.jpg", "open": "/me hello", "type": "opcomm" }];
		let Jso = JSON.stringify(xi, null, "\t");
		File.writeTo('.\\plugins\\CMENU\\hhh.json', Jso);
		let x = [{ "name": "test", "image": "https://z3.ax1x.com/2021/07/18/W31CBd.jpg", "open": "/me hello world", "type": "comm" }];
		let Js = JSON.stringify(x, null, "\t");
		File.writeTo('.\\plugins\\CMENU\\ooo.json', Js);
		logger.info('第一次加载CMENU,文件已自动创建!');
	}
}

/**
 * @param {Player} pl 
 * @param {Item} it 
 * @param {*} _bl 
 * @param {*} _side 
 * @param {*} _pos 
 */
function onUseItem(pl, it, _bl, _side, _pos) {
	if (!pl.xuid) { return; }
	if (it.type == "minecraft:clock") {
		if (!cache.has(pl.xuid)) {
			SendMenuForm(pl, "main");
			cache.set(pl.xuid, true);
			let xuid = pl.xuid;
			setTimeout(() => {
				cache.delete(xuid);
			}, 500);
		}
	}
}

function RegMenuCmd() {
	let nc = mc.newCommand("menu", "打开菜单", PermType.Any, 0x80, "cd");
	nc.overload([]);
	nc.setCallback((_cmd, ori, out, _res) => {
		let pl = ori.player;
		if (pl == null) {
			out.error("[CMENU] 此命令禁止非玩家执行!");
			return;
		}
		if (!pl.xuid) {
			out.error("[CMENU] 此命令禁止模拟玩家执行!");
			return;
		}
		SendMenuForm(pl, "main");
	});
	nc.setup();
}

function load() {
	logger.setTitle("CMENU");
	logger.setConsole(true, 4);
	mc.listen("onUseItemOn", onUseItem);
	mc.listen("onServerStarted", () => {
		try {
			RegMenuCmd();
		} catch (e) {
			logger.error("命令 menu&cd 注册失败!请检查是否有其他插件占用!");
			logger.error("Message: ", e.message);
		}
	});
	start();
	logger.info("加载完成！版本：0.2.5")
	logger.info("插件作者: 提米吖");
};
load();