
import { world, system, BlockPermutation } from '@minecraft/server';

const interactCooldown = new Set();

//============ Code to retrive details for everything to work :) =====================================================================================

function getPlayer() {
    const allPlayers = world.getAllPlayers();
    if (allPlayers.length === 0) {
      return undefined;
    }
  
    return allPlayers[0];
  }
  
  function getPlayerDimension() {
    const player = getPlayer();
    if (player === undefined) {
      return undefined;
    }
    return player.dimension;
  }
  
  function getPlayerLocation() {
    const player = getPlayer();
    if (player === undefined) {
      return undefined;
    }
    return player.location;
  }
  
  
  //============ Code to give starter book when player enters for first time =====================================================================================
  
  world.afterEvents.playerSpawn.subscribe((event) => {
  
      const player = event.player; // Player 
      const playerDimension = getPlayerDimension();
      const playerLocation = getPlayerLocation();
  
      if(player.getDynamicProperty("mbl_letter_oldPlayer") === undefined) {
      //  console.warn(`${player.name} joined for the first time, book.`); 
        playerDimension.spawnEntity("mbl_letter:letters_explainer_book", playerLocation); //change to starter book when ready
        player.setDynamicProperty("mbl_letter_oldPlayer", "true");
    };
  });

// Mapping of dye item typeIds to corresponding 'mbl_' state values
const dyeColorMap = {
    'minecraft:red_dye': 'red',
    'minecraft:white_dye': 'white',
    'minecraft:black_dye': 'black',
    'minecraft:blue_dye': 'blue',
    'minecraft:brown_dye': 'brown',
    'minecraft:cyan_dye': 'cyan',
    'minecraft:gray_dye': 'gray',
    'minecraft:green_dye': 'green',
    'minecraft:light_blue_dye': 'light_blue',
    'minecraft:light_gray_dye': 'light_gray',
    'minecraft:lime_dye': 'lime',
    'minecraft:magenta_dye': 'magenta',
    'minecraft:orange_dye': 'orange',
    'minecraft:pink_dye': 'pink',
    'minecraft:purple_dye': 'purple',
    'minecraft:yellow_dye': 'yellow'
};

world.afterEvents.itemUse.subscribe((event) => {
    const player = event.source;
    const item = event.itemStack;

    // Check if the item is a dye and retrieve the corresponding color
    const color = dyeColorMap[item?.typeId];
    if (!color) return;

    // Get the block the player is looking at within a 7-block range
    const block = player.getBlockFromViewDirection({
        includeLiquidBlocks: false,
        includePassableBlocks: true,
        maxDistance: 7,
    })?.block;

    if (!block) return;

    // Prevent rapid repeated interactions
    if (interactCooldown.has(player.name) || player.isSneaking) return;

    interactCooldown.add(player.name);
    system.runTimeout(() => interactCooldown.delete(player.name), 5);

    // Retrieve current block states
    const currentPermutation = block.permutation;
    const currentStates = currentPermutation.getAllStates();

    // Check if the block has the 'mbl_' state
    if (currentStates.hasOwnProperty('mbl_letter:color')) {
        // Update the 'mbl_' state to the corresponding color while preserving other states
        const updatedStates = { ...currentStates, 'mbl_letter:color': color };
        const newPermutation = BlockPermutation.resolve(block.typeId, updatedStates);
        block.setPermutation(newPermutation);

        // Optional: Play a sound to indicate success
        world.playSound('item.bone_meal.use', block.location);
    }
});


