// stringUtils.js
// String and general type manipulation utilities from tsunamiUtilityFunctions.js

// Capitalizes the first character, optionally lowercases the rest
export function capitalizeFirst(str, lowercaseRest = true) {
  let remainingChars = !lowercaseRest ? str.slice(1) : str.slice(1).toLowerCase();
  return str.charAt(0).toUpperCase() + remainingChars;
}

// Converts a string to snake_case
export function toSnakeCase(input) {
  return input.toLowerCase().replace(/\s+/g, "_");
}

// Converts a binary string to decimal number
export function binaryToDecimal(binaryStr) {
  return parseInt(binaryStr, 2);
}

// Converts a decimal number to a binary string, padded to 'pad' length
export function decimalToBinary(decimal, pad = 4) {
  return decimal.toString(2).padStart(pad, "0");
}

// Generates a random binary string of given length
export function randomBinaryString(length) {
  const randomInt = Math.floor(Math.random() * Math.pow(2, length));
  const binaryString = randomInt.toString(2);
  return binaryString.padStart(length, "0");
}

// Gets the namespace (before colon) from a string like 'namespace:value'
export function getNamespace(str) {
  const colonIndex = str.indexOf(":");
  return colonIndex !== -1 ? str.substring(0, colonIndex) : null;
}

// Removes the namespace (everything before and including colon)
export function stripNamespace(str) {
  return str.replace(/^.*?:/, "");
}

// Wraps a string into chunks of maxCharLength
export function wrapText(str, maxCharLength) {
  const words = str.split(" ");
  const chunks = [];
  let currentChunk = "";
  let currentLength = 0;
  for (const word of words) {
    const wordLength = word.length;
    if (currentLength + wordLength > maxCharLength) {
      chunks.push(currentChunk);
      currentChunk = "";
      currentLength = 0;
    }
    currentChunk += (currentChunk ? " " : "") + word;
    currentLength += wordLength + 1;
  }
  if (currentChunk) {
    chunks.push(currentChunk);
  }
  return chunks;
}

// Returns a shuffled copy of an array
export function shuffled(array) {
  const copy = [...array];
  for (let i = copy.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}

// Returns a hash code for a string
export function stringHash(str) {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i);
    hash = (hash << 5) - hash + charCode;
    hash = hash & hash;
  }
  return Math.abs(hash);
}
