import * as mc from "@minecraft/server";

export class cakeSupportManager {
    static beforeplace(data) {
        const block = data.block;
        const blockId = data.permutationToPlace.type.id;

        const north = block.north();
        const east = block.east();
        const south = block.south();
        const west = block.west();

        const northConnects = (north.hasTag("sgs_cake_support") && north.type.id == blockId);
        const eastConnects = (east.hasTag("sgs_cake_support") && east.type.id == blockId);
        const southConnects = (south.hasTag("sgs_cake_support") && south.type.id == blockId);
        const westConnects = (west.hasTag("sgs_cake_support") && west.type.id == blockId);

        mc.system.runTimeout(() => {
            if (northConnects) north.setPermutation(north.permutation.withState('sgs_cake:south', 1));
            if (eastConnects) east.setPermutation(east.permutation.withState('sgs_cake:west', 1));
            if (southConnects) south.setPermutation(south.permutation.withState('sgs_cake:north', 1));
            if (westConnects) west.setPermutation(west.permutation.withState('sgs_cake:east', 1));
        }, 0)

        data.permutationToPlace = mc.BlockPermutation.resolve(data.permutationToPlace.type.id, {
            'sgs_cake:north': northConnects ? 1 : 0,
            'sgs_cake:south': southConnects ? 1 : 0,
            'sgs_cake:east': eastConnects ? 1 : 0,
            'sgs_cake:west': westConnects ? 1 : 0
        });
    }

    static destroy(data) {

        const northConnects = data.brokenBlockPermutation.getState("sgs_cake:north");
        const eastConnects = data.brokenBlockPermutation.getState("sgs_cake:east");
        const southConnects = data.brokenBlockPermutation.getState("sgs_cake:south");
        const westConnects = data.brokenBlockPermutation.getState("sgs_cake:west");

        const blockId = data.brokenBlockPermutation.type.id;

        const block = data.block;
        const north = block.north();
        const east = block.east();
        const south = block.south();
        const west = block.west();

        if (northConnects && north.hasTag("sgs_cake_support")) north.setPermutation(north.permutation.withState('sgs_cake:south', 0));
        if (eastConnects && east.hasTag("sgs_cake_support")) east.setPermutation(east.permutation.withState('sgs_cake:west', 0));
        if (southConnects && south.hasTag("sgs_cake_support")) south.setPermutation(south.permutation.withState('sgs_cake:north', 0));
        if (westConnects && west.hasTag("sgs_cake_support")) west.setPermutation(west.permutation.withState('sgs_cake:east', 0));
    }
}
