import { decrementItemInHand } from '../util/utils';
import { Direction, ItemStack, world } from '@minecraft/server';
import { ModalFormData } from '@minecraft/server-ui';

export class McfSealItem {
	onUse(e, p) {
		const { source, itemStack } = e;
		if (!source?.isSneaking) return;
		const params = p.params;
		new ModalFormData()
		.title({ translate: `${params.title}` })
		.textField({ translate: "mcf.seal_item.textfield.sign" }, source.name, { tooltip: { translate: "mcf.seal_item.textfield.tooltip.sign" } })
		.show(source).then((r) => {
			if (r.canceled) return;
			const [ name ] = r.formValues;
			const finalName = name === "" ? source.name : name;
			const inv = source.getComponent("inventory").container;
			const sealedItem = new ItemStack(`${itemStack.typeId}_sealed`, 1);
			sealedItem.setDynamicProperty("mcf:signed_name", finalName );
			sealedItem.setDynamicProperty("mcf:container_id", itemStack.getDynamicProperty("mcf:container_id") );
			sealedItem.setLore([`§7From: ${finalName}`])
			inv.setItem(source.selectedSlotIndex, sealedItem);
			source.sendMessage({ translate: `${params.final_message}`, with: [ `${finalName}` ] })
		});
	}
}
export class McfPlacePresent {
	onUse(e) {
		const { source, itemStack } = e;
		if (itemStack.getDynamicProperty("mcf:container_id")) return;
		source.getComponent("inventory").container.setItem(
			source.selectedSlotIndex, new ItemStack(itemStack.typeId.replace("_sealed", ""), 1)
		);
	}
	onUseOn(e) {
		const { source, itemStack, block, blockFace } = e;
		if (blockFace !== Direction.Up) return;
		const setBlock = block.above()
		if (setBlock.isAir) return;
		const temp = block.dimension.spawnEntity("mr:temp", setBlock.bottomCenter());
		temp.setDynamicProperty("mcf:signed_name", itemStack.getDynamicProperty("mcf:signed_name"));
		temp.setDynamicProperty("mcf:container_id", itemStack.getDynamicProperty("mcf:container_id"));
		decrementItemInHand(source, true);
	}
}
export class McfOpenPresent {
	constructor() {
		this.onPlayerBreak = this.onPlayerBreak.bind(this);
		this.onPlayerInteract = this.onPlayerInteract.bind(this);
		this.beforeOnPlayerPlace = this.beforeOnPlayerPlace.bind(this);
	}
	openPresent(player, block) {
		const present = block.dimension.getEntitiesAtBlockLocation(block.location).find((en) => en.typeId === "mr:temp");
		if (!present) return player.sendMessage({ translate: "mcf.present.no_entity" });
		const presentId = present.getDynamicProperty("mcf:container_id");
		if (!presentId) return player.sendMessage({ translate: "mcf.present.no_data" });
		const containerData = world.structureManager.get(`mcf:container_${presentId}`);
		if (!containerData) return player.sendMessage({ translate: "mcf.present.no_exists" });
		world.structureManager.place(containerData, block.dimension, block.center(), { 
			includeBlocks: false, 
			includeEntities: true 
		});
		const nearbyEntities = block.dimension.getEntities({
			location: block.center(),
			maxDistance: 2,
			type: "mcf:dynamic_container"
		});
		const spawnedEntity = nearbyEntities.find(ent => 
			ent.getDynamicProperty("mcf:container_id") === presentId
		);
		if (spawnedEntity) {
			const inv = spawnedEntity.getComponent("inventory")?.container;
			for (let i = 0; i < inv.size; i++) {
				const tempI = inv.getItem(i);
				if (!tempI) continue;
				block.dimension.spawnItem(tempI, block.center());
			}
			player.sendMessage({ translate: "mcf.present.open", with: [ `${present.getDynamicProperty("mcf:signed_name")}` ] });
			block.dimension.playSound("random.levelup", block.center());
			spawnedEntity.remove();
			present.remove();
			world.structureManager.delete(`mcf:container_${presentId}`);
		}
	}
	isDiagonal(yRot) {
		const normalized = (yRot + 180);
		const sector = Math.floor((normalized + 22.5) / 45) % 8;
		return sector % 2 === 1; 
	}
	beforeOnPlayerPlace(e) {
		const { player } = e;
		const yRot = player.getRotation().y;
		const rotated = this.isDiagonal(yRot);
		e.permutationToPlace = e.permutationToPlace.withState("mcf:rotated", rotated);
	}
	onPlayerInteract(e) {
		this.openPresent(e.player, e.block);
		e.block.setType("minecraft:air");
	}
	onPlayerBreak(e) {
		this.openPresent(e.player, e.block);
	}
}
export class McfOpedSealedItem {
	onUse(e) {
		const { source, itemStack } = e;
		const sealItemId = itemStack.getDynamicProperty("mcf:container_id");
		if (!sealItemId) return source.sendMessage({ translate: "mcf.dynamic_container.no_data" });
		const containerData = world.structureManager.get(`mcf:container_${sealItemId}`);
		if (!containerData) return source.sendMessage({ translate: "mcf.dynamic_container.already_open" });
		world.structureManager.place(containerData, source.dimension, source.getHeadLocation(), { 
			includeBlocks: false, 
			includeEntities: true 
		});
		const nearbyEntities = source.dimension.getEntities({
			location: source.getHeadLocation(),
			maxDistance: 2,
			type: "mcf:dynamic_container"
		});
		const spawnedEntity = nearbyEntities.find(ent => 
			ent.getDynamicProperty("mcf:container_id") === sealItemId
		);
		if (spawnedEntity) {
			const inv = spawnedEntity.getComponent("inventory")?.container;
			for (let i = 0; i < inv.size; i++) {
				const tempI = inv.getItem(i);
				if (!tempI) continue;
				source.dimension.spawnItem(tempI, source.getHeadLocation());
			}
			spawnedEntity.remove();
			world.structureManager.delete(`mcf:container_${sealItemId}`);
			decrementItemInHand(source, true);
		}
	}
}