import { ItemStack, BlockPermutation, system, EquipmentSlot } from "@minecraft/server";
import { ModalFormData } from '@minecraft/server-ui';
import { frontBlockLocation, backBlockLocation, airBlocks, directionState } from '../util/globalVariables';
import { decrementItemInHand, itemApplyDamage, spawnEntityRotatedByBlock } from "../util/utils";

export class McfCeilingFan {
	onPlace(e, p) {
		const { block, dimension } = e;
		if (dimension.getEntitiesAtBlockLocation(block.location).find((en) => en.typeId === "mr:ceiling_fan")) return;
		dimension.spawnEntity("mr:ceiling_fan", block.center()).setProperty("mcf:variant", p.params.variant);
	}
}
export class McfFireAlarm {
	onPlace(e) {
		const { block, dimension } = e;
		dimension.spawnEntity("mr:fire_alarm", { x: block.x + 0.5, y: block.y + 0.8, z: block.z + 0.5 })
	}
	onPlayerInteract(e) {
		const { block, dimension } = e;
		const fireAlarmEntity = dimension.getEntitiesAtBlockLocation(block.location).find(en => en.matches({ type: "mr:fire_alarm" }));
		if (!fireAlarmEntity) return;
		if (!fireAlarmEntity.getProperty("mr:is_on")) return;
		fireAlarmEntity.setProperty("mr:is_on", false);
		block.setPermutation(block.permutation.withState("mr:lit", false));
	}
}
export class McfShowerHead {
	onPlayerInteract(e) {
		const { block, dimension } = e;
		const sh = dimension.getEntitiesAtBlockLocation(block.location).find((en) => en.typeId === "mcf:shower_head");
		if (sh) sh.remove();
		else dimension.spawnEntity("mcf:shower_head", block.center());
	}
}
export class McfPlaySound {
	onPlayerInteract(e, p) {
		e.block.setPermutation(e.block.permutation.withState("mr:pressed", true));
		e.dimension.playSound(p.params.sound, e.block.center());
	}
}
export class McfUnpressDoorBell {
	onTick(e) {
		e.block.setPermutation(e.block.permutation.withState("mr:pressed", false));
		e.dimension.playSound("random.lever_click", e.block.center(), { pitch: 0.5 });
	}
}
export class McfFairyLight{
	beforeOnPlayerPlace(e) {
		e.permutationToPlace = e.permutationToPlace.withState("mr:light", ((e.block.x + e.block.z) % 2 === 0));
	}
}
export class McfChimney {
	constructor() {
		this.onPlace = this.onPlace.bind(this);
		this.onPlayerBreak = this.onPlayerBreak.bind(this);
	}
	update(block) {
		block.setPermutation(block.permutation.withState("mr:top", block.above().hasTag("mcf:chimney")));
	}
	updateBelowBlock(block) {
		if (block.below().hasTag("mcf:chimney")) this.update(block.below());
	}
	onPlace(e) {
		this.update(e.block);
		this.updateBelowBlock(e.block);
	}
	onPlayerBreak(e) {
		this.updateBelowBlock(e.block);
	}
}
export class McfCampfire {
	onPlayerInteract(e) {
		const { player, block, dimension } = e;
		const item = player.getComponent("equippable")?.getEquipment(EquipmentSlot.Mainhand);
		if (item?.typeId === "minecraft:flint_and_steel") {
			itemApplyDamage(player, item);
			block.setPermutation(block.permutation.withState("mr:item_amount", 4));
		} else {
			block.setPermutation(block.permutation.withState("mr:item_amount", 2))
			dimension.spawnItem(new ItemStack(block.typeId, 1), player.location);
			dimension.playSound("block.itemframe.remove_item", block.center());
		}
	}
}
export class McfComputer {
	onPlace(e) { e.dimension.spawnEntity("mr:computer", e.block.bottomCenter()); }
}
export class McfToaster {
	onPlayerInteract(e) {
		const { player, block, dimension, faceLocation } = e;
		const direction = block.permutation.getState(directionState);
		const isNorthSouth = (direction === "north" || direction === "south")
		const coord = isNorthSouth ? faceLocation.z : faceLocation.x;
		const area = Number(coord < 0.5);
		const entities = dimension.getEntitiesAtBlockLocation(block.location).filter(en => en.typeId === "mr:toast_");
		if (player.isSneaking) {
			for (const en of entities) en.setProperty("mr:timer_start", true);
			return;
		}
		const item = player.getComponent("equippable")?.getEquipment(EquipmentSlot.Mainhand);
		if (item?.typeId !== "mr:bread_slice") return;
		if (entities.some(en => en.getProperty("mr:timer_start") || en.getProperty(`mr:toast_${area}`))) return;
		const toast = dimension.spawnEntity("mr:toast_", block.bottomCenter());
		toast.setProperty(`mr:toast_${area}`, true);
		toast.setRotation({ x: 0, y: isNorthSouth ? 0 : 90 });	
		toast.getComponent("inventory").container.setItem(0, new ItemStack(item.typeId, 1));
		decrementItemInHand(player);
		dimension.playSound("block.itemframe.add_item", block.center());
	}
}
export class McfBin {
	onPlayerInteract(e) {
		const { player, block, dimension } = e;
		const bin = dimension.getEntitiesAtBlockLocation(block.location).find((en) => en.typeId === "mcf:bin");
		if (!bin) return;
		const inv = bin.getComponent("inventory").container;
		if (inv.emptySlotsCount === inv.size) return player.onScreenDisplay.setActionBar({ translate: "mcf.bin.no_remove_items" });
		const isLocked = bin.getProperty("mcf:lock");
		if (isLocked) {
			dimension.playSound("mcf.bin_close", block.center());
			return inv.clearAll();
		}
		new ModalFormData()
		.title({ translate: "mcf.bin.form.title" })
		.label({ translate: "mcf.bin.form.label" })
		.toggle({ translate: "mcf.bin.form.toggle" }, { defaultValue: false, tooltip: { translate: "mcf.bin.form.toggle.tooltip" } })
		.submitButton({ translate: "mcf.bin.form.submit_button" })
		.show(player).then((r) => {
			if (r.canceled) return;
			bin.setProperty("mcf:lock", r.formValues[1]);
			dimension.playSound("mcf.bin_close", block.center());
			inv.clearAll();
		})
	}
}
export class McfClock {
	onPlace(e) {
		const direction = e.block.permutation.getState(directionState);
		spawnEntityRotatedByBlock("mr:digital_clock", e.block, direction, { init: e.block.bottomCenter() });
	}
}