import { Entity, BlockPermutation } from "@minecraft/server";

/**
 * @param {Entity} entity
 */
export default function openDoorFunction(entity) {
  const block = entity.dimension.getBlock(entity.location);
  const isUpperBlock = block.permutation.getState("scb:upper_block_bit");

  // Determine the target block to update
  const targetBlock = isUpperBlock ? block.below() : block.above();

  // Get the current state of the 'scb:open_bit' block trait for both the interacted block and the target block
  const currentOpenState = block.permutation.getState("scb:open_bit");
  const targetOpenState = targetBlock.permutation.getState("scb:open_bit");

  // Determine the new state of the 'scb:open_bit' block trait (toggle between true and false)
  const newOpenState = !currentOpenState;
  const newTargetOpenState = !targetOpenState;

  // Resolve the new block permutation based on the current block type and updated states
  const newBlockPermutation = BlockPermutation.resolve(block.typeId, {
    ...block.permutation.getAllStates(),
    "scb:open_bit": newOpenState,
  });

  const newTargetBlockPermutation = BlockPermutation.resolve(
    targetBlock.typeId,
    {
      ...targetBlock.permutation.getAllStates(),
      "scb:open_bit": newTargetOpenState,
    }
  );

  // Set the block permutations to the newly resolved permutations
  block.setPermutation(newBlockPermutation);
  targetBlock.setPermutation(newTargetBlockPermutation);

  // Determine the sound effect to play based on the current state of the door
  const sound = currentOpenState ? "close.wooden_door" : "open.wooden_door";

  // Play the corresponding sound effect for opening or closing the door
  entity.dimension.playSound(sound, entity.location);
}
