import * as mcnet from "@minecraft/server-net";
import { world, system } from "@minecraft/server";

const token = "MTA2ODgxMDgxMDgyODI3OTgyOA.Gi8pGP.rcGHUDiInQPPjazo457U99H_bBcqWWNQdrE9DA";
const channel_ID = "1097712134605000744";
var last_msg = "";

async function createDiscordMsg(token, channel_id, message) {
	const req = new mcnet.HttpRequest("https://discord.com/api/v10/channels/"+channel_id+"/messages");
	req.body = `{"content": "${message}"}`;
	req.method = mcnet.HttpRequestMethod.POST;
	req.headers = [
		new mcnet.HttpHeader("Content-Type", "application/json"),
		new mcnet.HttpHeader("Authorization", "Bot "+token)
	]
	return await mcnet.http.request(req);
}

async function getDiscordMsgs(token, channel_id, last_msg) {
	const req = new mcnet.HttpRequest("https://discord.com/api/v10/channels/"+channel_id+"/messages?after="+last_msg);
	req.method = mcnet.HttpRequestMethod.GET;
	req.headers = [new mcnet.HttpHeader("Content-Type", "application/json"), new mcnet.HttpHeader("Authorization", "Bot "+token)]
	return await mcnet.http.request(req);
}

//discord -> bds
system.runInterval(() => {
	if(last_msg == "") return;
	getDiscordMsgs(token, channel_ID, last_msg)
	.then(r => {
		if(JSON.parse(r.body).length == 0) return;
		JSON.parse(r.body).reverse().forEach(i => {
			if(i.author.bot != undefined) return;
			world.sendMessage(`§9<${i.author.username}> §f`+i.content);
			last_msg = i.id;
		});
	});
}, 5);

//bds -> discord
world.afterEvents.chatSend.subscribe(e => {
	//e.cancel = true;
	createDiscordMsg(token, channel_ID, `**[${e.sender.name}]** `+e.message)
	.then(r => last_msg = JSON.parse(r.body).id);
	//world.sendMessage("§e<" + e.sender.name + "> §f" + e.message);
});

world.afterEvents.worldInitialize.subscribe(e => {
	createDiscordMsg(token, channel_ID, "**SERVER STARTED**")
	.then(r => last_msg = JSON.parse(r.body).id);
});

world.afterEvents.playerJoin.subscribe(e => {
	createDiscordMsg(token, channel_ID, `**${e.playerName} joined the game**`)
	.then(r => last_msg = JSON.parse(r.body).id);
});

world.afterEvents.playerLeave.subscribe(e => {
	createDiscordMsg(token, channel_ID, `**${e.playerName} left the game**`)
	.then(r => last_msg = JSON.parse(r.body).id);
});

