/**
 * Force first letter uppercase on a word
 * @param string string
 * @returns
 */
export const makeFirstLetterUppercase = (string: string) => {
  if (string.length === 0) {
    return string;
  }
  return string[0].toUpperCase() + string.substring(1);
};

/**
 * Ensure all characters in the string are lowercase
 * @param str string to be encoded
 * @returns
 */
export const ensureAllLowerCase = (str?: any) => {
  if (!str) {
    return "";
  }

  if (typeof str !== "string") {
    return str;
  }

  return str.toLowerCase();
};

/**
 * Make string camelcase
 * all words start with uppercase except the first
 * @param str string to camelcaseify
 * @returns
 */
export const camelcaseify = (str: string): string => {
  if (typeof str !== "string") {
    return str;
  }
  if (!str) {
    return str;
  }
  const words = str
    .toLocaleLowerCase()
    .replaceAll("_", "-")
    .replaceAll(" ", "-")
    .split("-");
  let camelcaseProperty = "";
  words.forEach((word: string, i: number) => {
    if (i === 0) {
      camelcaseProperty = word;
    } else {
      camelcaseProperty = camelcaseProperty + makeFirstLetterUppercase(word);
    }
  });

  return camelcaseProperty;
};

export class StringUtils {
  static camelcaseify = camelcaseify;
  static ensureAllLowerCase = ensureAllLowerCase;
  static makeFirstLetterUppercase = makeFirstLetterUppercase;
  /**
   * Split and add a space before each capital letter
   * making camelcase words look like this:
   * "camelCase" => "Camel Case" so it is easier to read
   * @param str string to prettify
   */
  static prettify = (str: string): string => {
    return makeFirstLetterUppercase(str.split(/(?=[A-Z])/).join(" "));
  };
  /**
   * Remove special characters from string
   * make first letter uppercase
   * @param str string to be cleaned
   */
  static clean = (str: string): string => {
    return StringUtils.prettify(str.replace(/[^a-zA-Z0-9]/g, " ").trim());
  };

  static makeFirstLetterLowercase = (str: string): string => {
    if (str.length === 0) {
      return str;
    }
    return str[0].toLocaleLowerCase() + str.substring(1);
  };

  /**
   * Ensure that the string is in camelcase format and has no spaces
   * @param str string to ensure valid id format
   * @returns string in camelcase format and no spaces
   */
  static ensureValidIdFormat = (str: string) => {
    const camelCase = camelcaseify(str);

    if (camelCase) {
      return camelCase.replaceAll(" ", "").trim();
    }
    return undefined;
  };

  /**
   * Remove characters from string and make it look legible
   * less "code" like
   */
  static decodify = (str: string) => {
    if (!str) {
      return "";
    }
    if (typeof str !== "string") {
      return str;
    }
    return makeFirstLetterUppercase(
      str
        .replaceAll("_", " ")
        .replaceAll("-", " ")
        .replaceAll(".", " ")
        .replaceAll("  ", " ")
        .replaceAll(":", "")
    );
  };
}
