import { world } from "@minecraft/server";
import { solidBlock } from '../util/globalVariables';

export class McfBlockConnections {
	static connectionTags = new Set(["mc:bars", "mc:fence", "mc:wall", "mc:hedge", "mc:glass_pane"]);
	static updateConnections(block, tag) {
		let permutation = block.permutation;
		const neighbors = {"mc:n": block.north(),"mc:s": block.south(),"mc:w": block.west(),"mc:e": block.east()};
		for (const state in neighbors) {
			const neighbor = neighbors[state];
			permutation = permutation.withState(state, neighbor && (solidBlock.has(neighbor.typeId) || neighbor.hasTag("mc:solid_block") || neighbor.hasTag(tag)));
		}
		block.setPermutation(permutation);
	}
	static checkAdjacentBlocksForConnection(block) {
		const neighbors = [block.north(), block.south(), block.west(), block.east()];
		for (const neighbor of neighbors) {
			if (!neighbor || !neighbor.hasTag("mc:can_connect")) continue;
			for (const tag of this.connectionTags) {
				if (neighbor.hasTag(tag)) this.updateConnections(neighbor, tag);
			}
		}
	}
	static onPlace(e, p) { this.updateConnections(e.block, p.params.block_type) }
	static registerEvent() {
		world.afterEvents.playerPlaceBlock.subscribe((e) => {
			this.checkAdjacentBlocksForConnection(e.block);
		});
		world.afterEvents.playerBreakBlock.subscribe((e) => {
			this.checkAdjacentBlocksForConnection(e.block);
		});
	}
}