import * as mc from "@minecraft/server";
import { highlightBlock } from "../sgs_farm_lib";

export class workbenchManager {

    static beforeplaceTop(data) {
        const block = data.block;
        const below = block.below();
        if (below.hasTag("sgs_farm_workbench_base")) {
            data.permutationToPlace = mc.BlockPermutation.resolve(data.permutationToPlace.type.id, { 'sgs_farm:can_craft': 1, "minecraft:cardinal_direction": data.permutationToPlace.getState("minecraft:cardinal_direction") });

            mc.system.runTimeout(() => {
                if (data.permutationToPlace.type.id == "sgs_farm:fun_saw_hand") below.setPermutation(below.permutation.withState('sgs_farm:crafting_station', 1));
                if (data.permutationToPlace.type.id == "sgs_farm:fun_blueprint") below.setPermutation(below.permutation.withState('sgs_farm:crafting_station', 2));
                if (data.permutationToPlace.type.id == "sgs_farm:fun_paint_station") below.setPermutation(below.permutation.withState('sgs_farm:crafting_station', 3));

                highlightBlock(block);
                highlightBlock(below);
            }, 0)
        }
    }

    static destroyTop(data) {
        const block = data.block;
        const below = block.below();
        if (below.hasTag("sgs_farm_workbench_base")) {
            below.setPermutation(below.permutation.withState('sgs_farm:crafting_station', 0));
        }
    }

    static beforeplace(data) {
        const block = data.block;
        const direction = data.permutationToPlace.getState("minecraft:cardinal_direction");

        let right;
        let left;

        switch (direction) {
            case "north":
                right = block.east();
                left = block.west();
                break;
            case "east":
                right = block.south();
                left = block.north();
                break;
            case "west":
                right = block.north();
                left = block.south();
                break;
            case "south":
                right = block.west();
                left = block.east();
                break;
            default:
                break;
        }

        data.permutationToPlace = mc.BlockPermutation.resolve("sgs_farm:workbench", { 'minecraft:cardinal_direction': direction, 'sgs_farm:workbench_plank': getRandomInt(0, 3) });
    }

    //clean up connections made in case this block breaks
    static destroy(block) {
    }
}

function connectsTo(origin, target) {
    if (target.typeId == origin.typeId) if (origin.permutation.getState("minecraft:cardinal_direction") == target.permutation.getState("minecraft:cardinal_direction")) return true;
    return false;
}

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}