import { BlockPermutation } from '@minecraft/server';
import * as vector3 from "./vector3";
import * as game from "./game";
import * as chest_reward from "./chest_reward";

const airBlock = BlockPermutation.resolve("air");
const facingToRotation = [ 0, 0, 180, 0, 90, 270 ];


export async function onTick() {
	let allFurnitureSpawners = await game.getEntities("tcs_ohs:furniture_spawner");
	//if (allFurnitureSpawners.length > 0)
	//	game.debug("Found furniture spawners: "+allFurnitureSpawners.length);
	for(let furnitureSpawner of allFurnitureSpawners)
	{
		if (furnitureSpawner === undefined)
			continue;
		let cd = furnitureSpawner.getDynamicProperty("tcs_ohs_remove_cd");
		if (cd === undefined)
		{
			cd = 10;
			furnitureSpawner.setDynamicProperty("tcs_ohs_remove_cd", 10);
		}
		else
		{
			cd--;
			furnitureSpawner.setDynamicProperty("tcs_ohs_remove_cd", cd);
			if (cd === 0)
				furnitureSpawner.remove();
		}
	}
}


export async function onScriptEventReceive(event) //facing_direction:facing[down,up,north,south,west,east]
{
	let commandBlockLocation = vector3.Down.add(event.sourceEntity.location);

	let block = event.sourceEntity.dimension.getBlock(commandBlockLocation);
	let xRot = facingToRotation[block.permutation.getState("facing_direction")];
	
	await event.sourceEntity.dimension.setBlockPermutation(commandBlockLocation, airBlock);

	commandBlockLocation.y = Math.floor(commandBlockLocation.y);
	//await event.sourceEntity.dimension.spawnEntity(event.message, commandBlockLocation);
	let furnitureId = event.message;
	if (furnitureId === "tcs_ohs:hidden_treasure_chest") 
		furnitureId = "tcs_ohs:reward_chest";
	
	let furniture = await event.sourceEntity.dimension.spawnEntity(furnitureId, commandBlockLocation.toLocation());

	event.sourceEntity.setDynamicProperty("tcs_ohs_remove_cd", 10);
	await event.sourceEntity.triggerEvent("tcs_ohs:remove");
	event.sourceEntity.remove();

	//await game.runMobCommand(event.sourceEntity, `summon ${event.message} ${commandBlockLocation.toCommand()} ${xRot} 0`);
	game.runMobCommand(furniture, `tp @s ~ ~0.1 ~ ${xRot} 0`);
	if (furnitureId === "tcs_ohs:treasure_chest")
		await chest_reward.createTreasure(furniture);

	// Special handling for hidden treasure chest
	if (event.message === "tcs_ohs:hidden_treasure_chest") {
		furniture.triggerEvent("tcs_ohs:hide");
	}
	else if (event.message === "tcs_ohs:treasure_chest") {
		furniture.nameTag = "Treasure chest";
	}
}
