import { orderBy } from '../../internal/orderby.mjs';
import { isArrayFull } from '../../internal/type-checks.mjs';

function colorMapperValueToMaplibreExpression(value) {
  if (value.mode === "fixed") {
    return `'${value.defaultColor}'`;
  } else {
    if (!value.field) {
      return `'${value.defaultColor}'`;
    }
    if (!isArrayFull(value.colorStops)) {
      return `'${value.defaultColor}'`;
    }
    if (value.type === "string" || value.type === "select") {
      const cases = value.colorStops.map((stop) => {
        let operator;
        let stopValue = stop.value;
        if (stop.options?.regex) {
          operator = stop.options?.caseSensitive ? "~" : "~*";
          try {
            new RegExp(stopValue);
          } catch (e) {
            stopValue = "invalid_regex";
          }
        } else {
          operator = stop.options?.caseSensitive ? "==" : "=*";
        }
        return `@${value.field} ${operator} '${escapeMaplibreString(stopValue)}', '${stop.color}'`;
      }).join(",\n");
      return `
      case(
        ${cases},
        '${value.defaultColor}'
      )
    `;
    } else if (value.type === "number") {
      const cases = orderBy(value.colorStops, ["value"], ["desc"]).map((stop) => {
        return `@${value.field} >= to-number('${escapeMaplibreString(stop.value.toString())}', 0), '${stop.color}'`;
      }).join(",\n");
      return `
      case(
        @${value.field} == null, '${value.defaultColor}',
        ${cases},
        '${value.defaultColor}'
      )`;
    } else {
      return `'${value.defaultColor}'`;
    }
  }
}
function escapeMaplibreString(value) {
  return value.replace(/['\\]/g, "\\$&");
}

export { colorMapperValueToMaplibreExpression, escapeMaplibreString };
