import * as R from "ramda";

function transformStringBooleans(value: string) {
  if (value !== "true" && value !== "false") {
    return value;
  }

  return value === "true";
}

function transformStringNumbersBooleans(value: string | number): boolean {
  return value == "1"; // eslint-disable-line eqeqeq
}

function transformNumberInput(num: string | number) {
  return num === null || num === "" ? null : Number(num);
}

/**
 * fixes color - Zapp colors are AARRGGBB and output needs to be RRGGBBAA
 *
 * @param {string} input colorString
 * @returns {string} transformed color string
 */
function transformColorCode(colorHex: string): string {
  if (!colorHex) {
    return colorHex;
  }

  if (R.startsWith("rgba(", colorHex)) {
    return colorHex;
  }

  if (R.startsWith("#", colorHex) && colorHex.length === 9) {
    return `#${colorHex.slice(3, 9)}${colorHex.slice(1, 3)}`;
  }

  return colorHex;
}

/**
 * map of transformation function to apply to sanitize the fields
 * present in the manifest configuration
 */

/**
 * Applies a tranformation for a given type of manifest field. Falls back to
 * the identity function if the type is not declared in the transforms map
 * Curried function of the form applyTransform(type)(value)
 * @param {String} type to apply the transformation for
 * @returns {Function}
 * @param {Any} value to transform
 * @returns {Any} sanitized value
 */
function applyTransform(type: string) {
  const transforms = {
    switch: transformStringBooleans,
    checkbox: transformStringNumbersBooleans,
    number_input: transformNumberInput,
    color_picker: transformColorCode,
  };

  return transforms[type] || R.identity;
}

export { transformColorCode, applyTransform };
