import { BlockPermutation, Direction, system, world } from "@minecraft/server";
import { playSwingArm, shrinkIfInSurvival } from "../util/miscUtils";
import { getPlacementPosition, replaceBlock } from "../util/placementUtils";
import { SuppStates } from "../reg/suppStates";
import { McItems } from "../reg/mcItems";
import { flipDir, offsetPos } from "../util/dirUtils";
import { hasStrongClickAction, isReplaceable } from "../util/blockProperties";
//placement logic
function canReplaceStick(behind, face) {
    if (behind.typeId != "razz_sup:placeable_stick" /* SuppBlocks.PlaceableStick */)
        return false;
    return behind.permutation.getState(getStickAxis(face)) == false;
}
function getStickAxis(face) {
    switch (face) {
        case Direction.Up:
            return SuppStates.StickY;
        case Direction.Down:
            return SuppStates.StickY;
        case Direction.North:
            return SuppStates.StickZ;
        case Direction.South:
            return SuppStates.StickZ;
        case Direction.East:
            return SuppStates.StickX;
        case Direction.West:
            return SuppStates.StickX;
    }
}
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
    if (!event.isFirstEvent)
        return;
    const item = event.itemStack;
    if (!item || item.typeId != McItems.Stick)
        return;
    const block = event.block;
    const face = event.blockFace;
    const level = block.dimension;
    const player = event.player;
    let targetBlock = getPlacementPosition(block, face, b => isReplaceable(b) || canReplaceStick(b, face));
    const behind = offsetPos(targetBlock, flipDir(face));
    if (targetBlock && (player.isSneaking || !hasStrongClickAction(behind))) {
        event.cancel = true;
        system.run(() => {
            let permutation;
            if (targetBlock.typeId == "razz_sup:placeable_stick" /* SuppBlocks.PlaceableStick */) {
                permutation = targetBlock.permutation;
            }
            else {
                permutation = BlockPermutation.resolve("razz_sup:placeable_stick" /* SuppBlocks.PlaceableStick */);
            }
            permutation = permutation.withState(getStickAxis(face), true);
            replaceBlock(targetBlock, permutation);
            level.playSound("dig.wood", targetBlock.center(), { pitch: 1, volume: 0.8 });
            shrinkIfInSurvival(player, item);
            playSwingArm(player);
        });
    }
});
