/**
 * Force first letter lowercase on a word
 * @param string string
 * @returns
 */
export function forceFirstLetterLowercase(str: string) {
  if (str.length === 0) {
    return str;
  }
  return str.charAt(0).toLocaleLowerCase() + str.slice(1);
}

/**
 * Get css properties values
 * @param value object to be parsed
 * @returns css property value
 */
export function getLeafPropertyValue(
  value: object | { [property: string]: object } | string | number
): object | string | number {
  let propertyValue: object | string | number = value;

  if (typeof value === "string" || typeof value === "number") {
    propertyValue = value;
  }

  if (typeof value === "object") {
    const tempValue: { [property: string]: object } = value as {
      [property: string]: object;
    };
    const keys = Object.keys(value);

    keys.map((k) => {
      const v = tempValue[k];
      if (v && keys.length === 1) {
        propertyValue = getLeafPropertyValue(v);
      }
      return null;
    });
  }

  return propertyValue;
}

type NormalizedKeyEntry =
  | { [tokenId: string]: string | number }
  | string
  | number;
export const normalizeObjectKeys = (
  obj: NormalizedKeyEntry
): NormalizedKeyEntry => {
  if (typeof obj === "string" || typeof obj === "number") {
    return obj;
  }
  const normalized: { [tokenId: string]: string | number } = {};
  Object.keys(obj).forEach((key) => {
    const normalizedKey = forceFirstLetterLowercase(key);

    normalized[normalizedKey] = obj[key] as string;
  });
  return normalized;
};
/** Remove CSS properties from colors */
export function normalizeColors<T>(colors: object) {
  const tokenValue = colors;
  const normalizedTokens: T = {} as T;
  Object.keys(colors).forEach((token: string) => {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore: we know `token` is a valid key for `tokenValue`
    const colorTokenValue = tokenValue[token];

    if (colorTokenValue) {
      const value = normalizeObjectKeys(
        getLeafPropertyValue(colorTokenValue) as NormalizedKeyEntry
      );

      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore: we know `token` is a valid key for `tokenValue`
      normalizedTokens[forceFirstLetterLowercase(token)] = value;
    }
  });

  return normalizedTokens;
}
