import { Block, BlockPermutation, MolangVariableMap, system, world } from "@minecraft/server";
import { Helper } from "../utils/Helper";
import { Particle } from "../utils/Particle";
export class FatItem {
  static #HONEYCOMB_WAX_COLOR = { red: 0.91, green: 0.55, blue: 0.08 };
  static #FAT_WAX_COLOR = { red: 0.85, green: 0.70, blue: 0.45 };
  constructor() {
    this.onUseOn.bind(this);
  }
  onUseOn({ block, itemStack, source, usedOnBlockPermutation }) {
    if (!block.typeId.includes('copper') || block.typeId.includes('waxed')) return;
    const waxedId = block.typeId.replace('minecraft:', 'minecraft:waxed_');
    Helper.decreaseMainhandItemStack(source);
    FatItem.#createAndSpawnWaxParticle(block);
    world.playSound('copper.wax.on', block.location, {
      volume: 1.0,
      pitch: Math.random() * (1.2 - 0.8) + 0.8
    });
    if (!block.typeId.includes('_door')) {
      if (Object.keys(usedOnBlockPermutation.getAllStates()).length === 0) {
        block.setPermutation(BlockPermutation.resolve(waxedId.replace('_block', '')));
        return;
      }
      block.setPermutation(
        BlockPermutation.resolve(waxedId, usedOnBlockPermutation.getAllStates())
      );
      return;
    }
    const upperBlockBitState = block.permutation.getState('upper_block_bit');
    const basePermutation = !upperBlockBitState ? usedOnBlockPermutation : block.below().permutation;
    const directionState = basePermutation.getState('direction');
    const doorHingeBitState = basePermutation.getState('door_hinge_bit');
    const openBitState = basePermutation.getState('open_bit');
    const upBlock = !upperBlockBitState ? block.above().location : block.location;
    const downBlock = !upperBlockBitState ? block.location : block.below().location;
    const endFill = Helper.stringifyVector3(upBlock);
    const startFill = Helper.stringifyVector3(downBlock);
    const fillWithState = `${waxedId}["direction"=${directionState},"door_hinge_bit"=${doorHingeBitState},"open_bit"=${openBitState}]`
    source.runCommand(`/fill ${startFill} ${endFill} ${fillWithState} replace ${block.typeId}`);
  }
  static #createAndSpawnWaxParticle(block, quantity = 30) {
    const molang = new MolangVariableMap();
    const boundingBox = Particle.getBoundingBoxFrom(block, false, 0.1);
    for (let i = 0; i < quantity; i++) {
      const position = Particle.getRandomPositionInsideBoundingBox(boundingBox);
      molang.setVector3('variable.direction', block.location);
      molang.setColorRGB('variable.color', FatItem.#FAT_WAX_COLOR);
      block.dimension.spawnParticle('minecraft:wax_particle', position, molang);
    }
  }
}