const system = server.registerSystem(0, 0);

let logEvent = system.createEventData("minecraft:script_logger_config");
logEvent.data.log_errors = true;
logEvent.data.log_warnings = true;
logEvent.data.log_information = true;
system.broadcastEvent("minecraft:script_logger_config", logEvent);

let worldEdit = {
	pos1: null,
	pos2: null,
	nextPos: 1 // Either 1 or 2, the next position that should be changed
};

const worldEditTools = {
	fill: {
		positions: ["111222"],
		message: "This area has been filled with"
	},
	fill_borders: {
		positions: [
			"111112",
			"111121",
			"111211",
			"111221",
			"111122",
			"111212",
			"112222",
			"121222",
			"211222",
			"221222",
			"122222"
		],
		message: "This area's borders have been filled with"
	},
	fill_walls: {
		positions: [
			"111112",
			"111211",
			"111221",
			"111122",
			"112222",
			"211222"
		],
		message: "This area's walls have been filled with"
	}
}

system.initialize = () => {

	// Communicate with functions
	system.listenForEvent("minecraft:entity_death", event => {

		if (!system.hasComponent(event.data.entity, "minecraft:nameable")) return;

		let name = system.getComponent(event.data.entity, "minecraft:nameable").data.name;

		if (system.getEntitiesFromQuery(system.registerQuery()).filter(entity => entity.__identifier__ == "minecraft:player") > 1 && name.startsWith("worldedit-")) {
			system.sendChatMessage("§cWorldEdit does not work in multiplayer yet, sorry!");
			return;
		}

		if (name == "worldedit-reset") {

			worldEdit.pos1 = null;
			worldEdit.pos2 = null;
			worldEdit.nextPos = 1;
			system.sendChatMessage("All WorldEdit data has been §creset§f.")

		} else if (name == "worldedit-clone") {

			if (!worldEdit.pos1 || !worldEdit.pos2) {
				system.sendChatMessage("§cYou must select 2 positions before you can use WorldEdit.");
				return;
			}

			let playerCoords = system.getComponent(system.getEntitiesFromQuery(system.registerQuery()).filter(entity => entity.__identifier__ == "minecraft:player")[0], "minecraft:position").data;

			system.execute(`/clone ${worldEdit.pos1.x} ${worldEdit.pos1.y} ${worldEdit.pos1.z} ${worldEdit.pos2.x} ${worldEdit.pos2.y} ${worldEdit.pos2.z} ${playerCoords.x} ${playerCoords.y} ${playerCoords.z}`);

			system.sendChatMessage("§aThis area has been cloned.");

		} else if (worldEditTools[name.replace(/worldedit-/, "")]) {

			if (!worldEdit.pos1 || !worldEdit.pos2) {
				system.sendChatMessage("§cYou must select 2 positions before you can use WorldEdit.");
				return;
			}

			let player = system.getEntitiesFromQuery(system.registerQuery()).filter(entity => entity.__identifier__ == "minecraft:player")[0];
			let handItem = system.getComponent(player, "minecraft:hand_container").data[0].item.replace("minecraft:", "");

			if (handItem == "fireball") {
				system.sendChatMessage("§cMake sure you hold the block you want to use in your hand while typing the command.");
				return;
			}

			if (handItem == "undefined") handItem = "air";

			worldEditTools[name.replace(/worldedit-/, "")].positions.forEach(position => {
				system.execute(`/fill ${worldEdit[`pos${position.charAt(0)}`].x} ${worldEdit[`pos${position.charAt(1)}`].y} ${worldEdit[`pos${position.charAt(2)}`].z} ${worldEdit[`pos${position.charAt(3)}`].x} ${worldEdit[`pos${position.charAt(4)}`].y} ${worldEdit[`pos${position.charAt(5)}`].z} ${handItem}`);
			});

			system.sendChatMessage(`§a${worldEditTools[name.replace(/worldedit-/, "")].message} §6${handItem.replace(/_/g, " ")}§a.`)

		}

	});

	system.listenForEvent("minecraft:block_interacted_with", event => {

		let handItem = system.getComponent(event.data.player, "minecraft:hand_container").data[0].item;

		// If the person right-clicked their fireball
		if (handItem == "minecraft:fireball") {

			worldEdit[`pos${worldEdit.nextPos}`] = event.data.block_position;

			system.sendChatMessage(`Position ${worldEdit.nextPos} is now set to §3${event.data.block_position.x} ${event.data.block_position.y} ${event.data.block_position.z}`);

			if (worldEdit.nextPos == 1) worldEdit.nextPos = 2;
			else worldEdit.nextPos = 1;

			let tickingArea = system.getComponent(event.data.player, "minecraft:tick_world").data.ticking_area;

			let pos = event.data.block_position;

			// Replace all fire with air
			system.execute(`/fill ${pos.x - 1} ${pos.y - 1} ${pos.z - 1} ${pos.x + 1} ${pos.y + 1} ${pos.z + 1} air 0 replace fire`);

		}

	});

}

system.sendChatMessage = (msg, target = "@a") => {

	let commandEvent = system.createEventData("minecraft:execute_command");
	commandEvent.data.command = `/tellraw ${target} {"rawtext":[{"text":"${msg}"}]}`;
	system.broadcastEvent("minecraft:execute_command", commandEvent);

}

system.execute = cmd => {

	let commandEvent = system.createEventData("minecraft:execute_command");
	commandEvent.data.command = cmd;
	system.broadcastEvent("minecraft:execute_command", commandEvent);

}
