import { BlockPermutation } from '@minecraft/server';
import { airBlocks, directionState, getBackBlock, getFrontBlock } from '../util/globalVariables';

export class McfModernStairs {
	constructor() {
		this.onPlace = this.onPlace.bind(this);
		this.onStepOn = this.onStepOn.bind(this);
		this.onPlayerBreak = this.onPlayerBreak.bind(this);
	}
	update(block, direction) {
		block.setPermutation(block.permutation
			.withState("mr:top", getBackBlock(block, direction)?.above()?.hasTag("mcf:is_stairs") ?? false)
			.withState("mr:bottom", getFrontBlock(block, direction)?.below()?.hasTag("mcf:is_stairs") ?? false)
		)
	}
	updateNearest(block, direction) {
		const backBlock = getBackBlock(block, direction)?.above();
		const frontBlock = getFrontBlock(block, direction)?.below();
		if (backBlock?.hasTag("mcf:is_stairs")) this.update(backBlock, backBlock.permutation.getState(directionState));
		if (frontBlock?.hasTag("mcf:is_stairs")) this.update(frontBlock, frontBlock.permutation.getState(directionState));
	}
	onStepOn(e) {
		const { block, entity } = e;
		if (!entity?.matches({ type: "minecraft:player" })) return;
		const aboveBlock = block.above();
		if (airBlocks.includes(aboveBlock?.typeId)) aboveBlock.setPermutation(BlockPermutation.resolve("mr:stairs_top", { [directionState]: block.permutation.getState(directionState) }));
	}
	onPlace(e) {
		const direction = e.block.permutation.getState(directionState);
		this.update(e.block, direction);
		this.updateNearest(e.block, direction);
	}
	onPlayerBreak(e) {
		this.updateNearest(e.block, e.brokenBlockPermutation.getState(directionState));
	}
}
export class McfModernStairsCheck {
	onTick(e) {
		const { block, dimension } = e;
		const arrayCheck = dimension.getEntities({ location: block.location, type: "minecraft:player", maxDistance: 4 });
		if (arrayCheck.length === 0) block.setType("minecraft:air");
	}
}