"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.validateColorRanges = exports.validateColorRange = exports.getErrorMessages = exports.allRangesValid = void 0;
var _i18n = require("@kbn/i18n");
var _color_manipulation = require("../../../color_manipulation");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

/** @internal **/

/** @internal **/

/** @internal **/
const getErrorMessages = colorRangesValidity => {
  return Array.from(new Set(Object.values(colorRangesValidity).map(item => item.errors).flat().map(item => {
    switch (item) {
      case 'invalidColor':
      case 'invalidValue':
        return _i18n.i18n.translate('coloring.dynamicColoring.customPalette.invalidValueOrColor', {
          defaultMessage: 'At least one color range contains the wrong value or color'
        });
      case 'greaterThanMaxValue':
        return _i18n.i18n.translate('coloring.dynamicColoring.customPalette.invalidMaxValue', {
          defaultMessage: 'Maximum value must be greater than preceding values'
        });
      case 'percentOutOfBounds':
        return _i18n.i18n.translate('coloring.dynamicColoring.customPalette.invalidPercentValue', {
          defaultMessage: 'Percent values must be between 0 and 100'
        });
      default:
        return '';
    }
  })));
};

/** @internal **/
exports.getErrorMessages = getErrorMessages;
const validateColorRange = (colorRange, accessor, isPercent) => {
  const errors = [];
  const value = colorRange[accessor];
  if (Number.isNaN(value)) {
    errors.push('invalidValue');
  }
  if (accessor === 'end') {
    if (colorRange.start > colorRange.end) {
      errors.push('greaterThanMaxValue');
    }
  } else if (!(0, _color_manipulation.isValidColor)(colorRange.color)) {
    errors.push('invalidColor');
  }
  if (isPercent) {
    if (![-Infinity, Infinity].includes(value) && (value < 0 || value > 100)) {
      errors.push('percentOutOfBounds');
    }
  }
  return {
    isValid: !errors.length,
    errors
  };
};
exports.validateColorRange = validateColorRange;
const validateColorRanges = (colorRanges, isPercent) => {
  const validations = colorRanges.reduce((acc, item, index) => ({
    ...acc,
    [index]: validateColorRange(item, 'start', isPercent)
  }), {});
  return {
    ...validations,
    last: validateColorRange(colorRanges[colorRanges.length - 1], 'end', isPercent)
  };
};
exports.validateColorRanges = validateColorRanges;
const allRangesValid = (colorRanges, isPercent) => {
  return Object.values(validateColorRanges(colorRanges, isPercent)).every(colorRange => colorRange.isValid);
};
exports.allRangesValid = allRangesValid;