import { BlockPermutation } from "@minecraft/server";
import { flipDir, getADirection, isFacingSameWay, isSameAxis, offsetPos, setADirectionState } from "../util/dirUtils";
import { McBlocks } from "../reg/mcBlocks";
import { windRope } from "./ropeStuff";
import { SuppStates } from "../reg/suppStates";
import { worldProxy } from "../worldProxy";
export const PulleyComponent = {
    onTick(event) {
        const block = event.block;
        if (!block.isValid())
            return;
        const power = block.getRedstonePower() | 0;
        if (power > 0 != block.permutation.getState(SuppStates.Powered)) {
            block.setPermutation(block.permutation.withState(SuppStates.Powered, power > 0));
        }
        const interval = 10;
        //tick starts when block is placed. syncing with tick time would be tricky and not worth it
        if (power > 0 && worldProxy.getTickTime() % interval == 0) {
            let dir = getADirection(block); // perm
            const facingBlock = offsetPos(block, dir);
            const oppositeDir = flipDir(dir);
            let behindBlock = block;
            while (true) {
                behindBlock = offsetPos(behindBlock, oppositeDir);
                if (!behindBlock || !behindBlock.isValid())
                    return;
                if (behindBlock.typeId != block.typeId || !isFacingSameWay(behindBlock, block)) {
                    break;
                }
            }
            //maybe add tag
            if (isValidRope(behindBlock, dir)) {
                const pushSuccess = windRope(facingBlock, dir, 1, getRopeWithDir(behindBlock.typeId, dir), McBlocks.Air);
                //this should always succeed
                if (pushSuccess) {
                    block.dimension.playSound("item.spyglass.use", block.center(), { pitch: 0.8, volume: 1 });
                    //TODO: sdd pulley push sound
                    windRope(behindBlock, oppositeDir, -1, BlockPermutation.resolve(McBlocks.Air), behindBlock.typeId);
                }
            }
        }
    }
};
function isValidRope(behindBlock, myDir) {
    if (behindBlock.typeId == "razz_sup:rope" /* SuppBlocks.Rope */ || behindBlock.typeId == McBlocks.Chain) {
        const behindDir = getADirection(behindBlock);
        if (isSameAxis(myDir, behindDir)) {
            return true;
        }
    }
    return false;
}
function getRopeWithDir(rope, dir) {
    let perm = BlockPermutation.resolve(rope);
    perm = setADirectionState(perm, dir);
    return perm;
}
