/**
 * DSS State System Utilities
 * Utility functions for the block state cycling system
 */

import { world, system } from "@minecraft/server";
import { DEBUG, UI_DELAY } from "./dss_state_config.js";

/**
 * Debug logging function with consistent formatting
 * @param {string} message - The message to log
 * @param {string} type - The type of log ("log", "warn", "error")
 * @param {string} prefix - The prefix for the log message
 */
export function debug(message, type = "log", prefix = "[DSS-State]") {
    if (!DEBUG) return;
    
    const fullMessage = `${prefix} ${message}`;
    
    switch (type) {
        case "log":
        case "info":
            console.log(`[§2INFO§r] ${fullMessage}`);
            break;
        case "warn":
        case "warning":
            console.warn(`[§6WARN§r] ${fullMessage}`);
            break;
        case "error":
            console.error(`[§4ERROR§r] ${fullMessage}`);
            break;
        default:
            console.log(`[§2INFO§r] ${fullMessage}`);
            break;
    }
}

/**
 * Format a block position as a string
 * @param {object} location - Block location object with x, y, z
 * @returns {string} Formatted position string
 */
export function formatPos(location) {
    if (!location || typeof location !== 'object') {
        return 'invalid_position';
    }
    return `${location.x},${location.y},${location.z}`;
}

/**
 * Send a message to a player with optional delay
 * @param {object} player - The player to send the message to
 * @param {string} message - The message to send
 * @param {number} delay - Optional delay in ticks
 */
export function sendPlayerMessage(player, message, delay = UI_DELAY) {
    if (!player || !message) return;
    
    if (delay > 0) {
        system.runTimeout(() => {
            player.sendMessage(message);
        }, delay);
    } else {
        player.sendMessage(message);
    }
}

/**
 * Play a sound for a player with optional delay
 * @param {object} player - The player to play the sound for
 * @param {string} sound - The sound ID to play
 * @param {number} delay - Optional delay in ticks
 */
export function playPlayerSound(player, sound, delay = UI_DELAY) {
    if (!player || !sound) return;
    
    if (delay > 0) {
        system.runTimeout(() => {
            player.playSound(sound);
        }, delay);
    } else {
        player.playSound(sound);
    }
}

/**
 * Get the block type suffix from a block identifier
 * @param {string} blockId - The block identifier
 * @returns {string|null} The suffix (_12, _13, _14) or null if not found
 */
export function getBlockTypeSuffix(blockId) {
    if (!blockId || typeof blockId !== 'string') return null;
    
    const suffixes = ['_12', '_13', '_14'];
    for (const suffix of suffixes) {
        if (blockId.includes(suffix)) {
            return suffix;
        }
    }
    return null;
}

/**
 * Check if a block is a DSS state block
 * @param {object} block - The block to check
 * @returns {boolean} True if it's a DSS state block
 */
export function isDssStateBlock(block) {
    if (!block || !block.typeId) return false;
    
    const suffix = getBlockTypeSuffix(block.typeId);
    return suffix !== null;
}

/**
 * Get the current state of a block
 * @param {object} block - The block to check
 * @returns {string|null} The current state or null if not found
 */
export function getCurrentState(block) {
    if (!block || !block.permutation) return null;
    
    return block.permutation.getState("dss_block:state");
}

/**
 * Set the state of a block
 * @param {object} block - The block to modify
 * @param {string} newState - The new state to set
 * @returns {boolean} True if successful
 */
export function setBlockState(block, newState) {
    if (!block || !block.permutation || !newState) return false;
    
    const newPermutation = block.permutation.withState("dss_block:state", newState);
    block.setPermutation(newPermutation);
    return true;
}

/**
 * Get the next state in the cycle
 * @param {string} currentState - The current state
 * @param {string[]} availableStates - Array of available states
 * @returns {string} The next state
 */
export function getNextState(currentState, availableStates) {
    if (!currentState || !availableStates || availableStates.length === 0) {
        return availableStates && availableStates.length > 0 ? availableStates[0] : "1";
    }
    
    const currentIndex = availableStates.indexOf(currentState);
    const nextIndex = (currentIndex + 1) % availableStates.length;
    return availableStates[nextIndex];
}

/**
 * Plays a sound at a block's location
 * @param {object} block - The block to play the sound at
 * @param {string} soundId - The ID of the sound to play
 * @param {object} options - Optional parameters for volume and pitch
 */
export function playSoundAtBlock(block, soundId, options = { volume: 1.0, pitch: 1.0 }) {
    if (!block || !soundId) return;
    
    if (block.typeId.includes("curtain")) {
        soundId = "armor.equip_leather";
    } else if (block.typeId.includes("window")) {
        soundId = "open.wooden_trapdoor";
    } else if (block.typeId.includes("manhole")) {
        soundId = "block.grindstone.use";
    } else if (block.typeId.includes("dumpster")) {
        soundId = "open.iron_trapdoor";
    }

    block.dimension.playSound(soundId, block.location, options);
} 