import { updateVertical, updateVerticalNearestBlocks } from './Global'

export class McfLamp {
	constructor() {
		this.onPlace = this.onPlace.bind(this);
		this.onPlayerBreak = this.onPlayerBreak.bind(this);
		this.onPlayerInteract = this.onPlayerInteract.bind(this);
	}
	findTopLamp(block, maxHeight = 32) {
		if (maxHeight <= 0) return block;
		const blockAbove = block.above();
		if (blockAbove.typeId === block.typeId) return this.findTopLamp(blockAbove, maxHeight - 1);
		return block;
	}
	onPlace(e) {
		updateVertical(e.block);
		updateVerticalNearestBlocks(e.block, e.block.typeId);
	}
	onPlayerBreak(e) {
		updateVerticalNearestBlocks(e.block, e.brokenBlockPermutation.type.id)
	}
	onPlayerInteract(e) {
		const { block, dimension } = e;
		const top = this.findTopLamp(block);
		const litState = top.permutation.getState("mr:lit");
		top?.setPermutation(top.permutation.withState("mr:lit", !litState));
		dimension.playSound("random.lever_click", block.center(), { pitch: litState ? 0.5 : 0.6 });
	}
}