import { Block, BlockPermutation, Dimension, Player, system } from "@minecraft/server";
import { filterCoordinateTags, findUUIDByCoordinates, v4Coords } from "../../library/uuidCoords";
import { setBlockToAir } from "../../library/blockManager";

/**
 * Evento Place del componente teleportCheckpointComponent
 * @param {{player: Player, face: string, permutationToPlace: BlockPermutation, cancel: boolean, block: Block, dimension: Dimension}} event 
 */
export const teleportCheckpointPlaceEvent = ({ player, face, permutationToPlace, cancel, dimension, block }) => {
    teleportCheckPoint(player, block, dimension);
}

/**
* Evento OnIteract del componente teleportCheckpointComponent
* @param {{player: Player, block: Block, dimension: Dimension}} event 
*/
export const teleportCheckpointInteractEvent = ({ player, block, dimension }) => {
    removeTeleport(player, block, dimension);
}


/**
 * UUID Coordinates
 * @param {Player} player
 * @param {Block} block 
 * @param {Dimension} dimension 
 */
const teleportCheckPoint = (player, block, dimension) => {
    system.run(() => { 
        const uuidCoord = v4Coords(block.x, block.y, block.z, dimension.id);
        player.addTag(uuidCoord);
    })
}

/**
 * Remove Teleport
 * @param {Player} player Datos del jugador
 * @param {Block} block Datos del bloque
 * @param {Dimension} dimencion Dimencion del bloque
 */

const removeTeleport = (player, block, dimencion) => {
    system.run(() => {
        try {
            const playerDown = { x: player.location.x, y: player.location.y - 1, z: player.location.z };

            const blockDown = dimencion.getBlock(playerDown)
            if (blockDown.location.x === block.location.x && blockDown.location.y === block.location.y && blockDown.location.z === block.location.z) return;

            const playerTags = filterCoordinateTags(player.getTags(), player.dimension.id);
            player.removeTag(findUUIDByCoordinates(block.location, playerTags));
            setBlockToAir(block, dimencion)
        } catch  { }
    })
}