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

const MAX_COOP_HEIGHT = 3;
const MAX_HUTCH_HEIGHT = 2;

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


        const up = block.above();
        const down = block.below();

        const upConnects = (up.hasTag("sgs_farm_coop") && up.type.id == blockId);
        const downConnects = (down.hasTag("sgs_farm_coop") && down.type.id == blockId);

        mc.system.runTimeout(() => {
            if (downConnects) down.setPermutation(down.permutation.withState('sgs_farm:roof', 0));
        }, 0)

        data.permutationToPlace = mc.BlockPermutation.resolve(data.permutationToPlace.type.id, {
            'minecraft:cardinal_direction': data.permutationToPlace.getState("minecraft:cardinal_direction"),
            'sgs_farm:roof': upConnects ? 0 : 1,
        });
    }

    static destroy(data) {

        const downConnects = data.destroyedBlockPermutation.getState("sgs_farm:roof");
        const block = data.block;
        const down = block.below();

        if (downConnects && down.hasTag("sgs_farm_coop")) down.setPermutation(down.permutation.withState('sgs_farm:roof', 1));
    }
}

stackBedCheck();

function stackBedCheck() {
    mc.system.afterEvents.scriptEventReceive.subscribe((eventData) => {
        const { id, sourceEntity, message } = eventData;
        if (sourceEntity == undefined) return;

        if (id == "sgs_farm:check_chicken_coop") {
            const location = sourceEntity.location;
            const dimension = sourceEntity.dimension.id;
            const block = mc.world.getDimension(dimension).getBlock(location);

            if (!block.hasTag("sgs_farm_coop")) return;

            let coop_block = block;
            for (let index = 1; index < MAX_COOP_HEIGHT; index++) {
                if (coop_block.above().hasTag("sgs_farm_coop")) {
                    if (isCoopFree(coop_block.above())) coop_block = coop_block.above();
                }
            }
            const xvar = (-0.5 + Math.random()) * 0.5;
            const zvar = (-0.5 + Math.random()) * 0.5;

            const teleport_target = { x: coop_block.bottomCenter().x + xvar, y: coop_block.bottomCenter().y + 0.4, z: coop_block.bottomCenter().z + zvar }
            sourceEntity.teleport(teleport_target);
            return;
        };

        //try to center a rabbit into the hutch when sleep begins
        if (id == "sgs_farm:check_rabbit_hutch") {
            const location = sourceEntity.location;
            const dimension = sourceEntity.dimension.id;
            const block = mc.world.getDimension(dimension).getBlock(location);

            if (!block.hasTag("sgs_farm_rabbit_hutch")) return;

            let hutch_block = block;
            for (let index = 1; index < MAX_HUTCH_HEIGHT; index++) {
                if (hutch_block.above().hasTag("sgs_farm_rabbit_hutch")) {
                    if (isCoopFree(hutch_block.above())) hutch_block = hutch_block.above();
                }
            }

            //slight offset
            const xvar = (-0.5 + Math.random()) * 0.5;
            const zvar = (-0.5 + Math.random()) * 0.5;

            const teleport_target = { x: hutch_block.bottomCenter().x + xvar, y: hutch_block.bottomCenter().y + 0.4, z: hutch_block.bottomCenter().z + zvar }
            sourceEntity.teleport(teleport_target);
            return;
        };
    })
}

function isCoopFree(block) {
    if (mc.world.getDimension(block.dimension.id).getEntities({ location: block.center(), maxDistance: 0.5 }).length > 0) return false;
    return true;
}