"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ColorRangeItem = ColorRangeItem;
var _i18n = require("@kbn/i18n");
var _useUpdateEffect = _interopRequireDefault(require("react-use/lib/useUpdateEffect"));
var _react = _interopRequireWildcard(require("react"));
var _react2 = require("@emotion/react");
var _eui = require("@elastic/eui");
var _color_manipulation = require("../../../color_manipulation");
var _palettes = require("../../../palettes");
var _related = require("../assets/related");
var _utils = require("./utils");
var _color_ranges_item_buttons = require("./color_ranges_item_buttons");
var _color_ranges_context = require("./color_ranges_context");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * 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.
 */

const getMode = (index, isLast, continuity) => {
  if (!isLast && index > 0) {
    return 'value';
  }
  return (isLast ? _palettes.checkIsMaxContinuity : _palettes.checkIsMinContinuity)(continuity) ? 'auto' : 'edit';
};
const getActionButton = mode => {
  if (mode === 'value') {
    return _color_ranges_item_buttons.ColorRangeDeleteButton;
  }
  return mode === 'edit' ? _color_ranges_item_buttons.ColorRangeAutoDetectButton : _color_ranges_item_buttons.ColorRangeEditButton;
};
const getAppend = (rangeType, mode) => {
  const items = [];
  if (rangeType === 'percent') {
    items.push('%');
  }
  return items;
};
function ColorRangeItem({
  accessor,
  index,
  colorRange,
  rangeType,
  colorRanges,
  validation,
  continuity,
  dispatch
}) {
  var _validation$isValid;
  const {
    dataBounds,
    palettes
  } = (0, _react.useContext)(_color_ranges_context.ColorRangesContext);
  const [popoverInFocus, setPopoverInFocus] = (0, _react.useState)(false);
  const [localValue, setLocalValue] = (0, _react.useState)(colorRange[accessor]);
  const isLast = (0, _utils.isLastItem)(accessor);
  const mode = getMode(index, isLast, continuity);
  const isDisabled = mode === 'auto';
  const isColorValid = (0, _color_manipulation.isValidColor)(colorRange.color);
  const ActionButton = getActionButton(mode);
  const isValid = (_validation$isValid = validation === null || validation === void 0 ? void 0 : validation.isValid) !== null && _validation$isValid !== void 0 ? _validation$isValid : true;
  const {
    euiTheme
  } = (0, _eui.useEuiTheme)();
  const onLeaveFocus = (0, _react.useCallback)(e => {
    var _colorRanges$start, _colorRanges, _colorRanges$start2, _colorRanges2, _colorRanges$end, _colorRanges3, _e$currentTarget;
    const prevStartValue = (_colorRanges$start = (_colorRanges = colorRanges[index - 1]) === null || _colorRanges === void 0 ? void 0 : _colorRanges.start) !== null && _colorRanges$start !== void 0 ? _colorRanges$start : Number.NEGATIVE_INFINITY;
    const nextStartValue = (_colorRanges$start2 = (_colorRanges2 = colorRanges[index + 1]) === null || _colorRanges2 === void 0 ? void 0 : _colorRanges2.start) !== null && _colorRanges$start2 !== void 0 ? _colorRanges$start2 : Number.POSITIVE_INFINITY;
    const lastEndValue = (_colorRanges$end = (_colorRanges3 = colorRanges[colorRanges.length - 1]) === null || _colorRanges3 === void 0 ? void 0 : _colorRanges3.end) !== null && _colorRanges$end !== void 0 ? _colorRanges$end : Number.POSITIVE_INFINITY;
    const shouldSort = colorRange.start > nextStartValue || prevStartValue > colorRange.start || !isLast && colorRange.start > lastEndValue;
    const isFocusStillInContent = ((_e$currentTarget = e.currentTarget) === null || _e$currentTarget === void 0 ? void 0 : _e$currentTarget.contains(e.relatedTarget)) || popoverInFocus;
    if (shouldSort && !isFocusStillInContent) {
      dispatch({
        type: 'sortColorRanges',
        payload: {
          dataBounds,
          palettes
        }
      });
    }
  }, [colorRange.start, colorRanges, dispatch, index, popoverInFocus, dataBounds, palettes, isLast]);
  const onValueChange = (0, _react.useCallback)(({
    target: {
      value: targetValue
    }
  }) => {
    setLocalValue(targetValue);
    dispatch({
      type: 'updateValue',
      payload: {
        index,
        value: targetValue,
        accessor,
        dataBounds,
        palettes
      }
    });
  }, [dispatch, index, accessor, dataBounds, palettes]);
  const onUpdateColor = (0, _react.useCallback)(color => {
    dispatch({
      type: 'updateColor',
      payload: {
        index,
        color,
        dataBounds,
        palettes
      }
    });
  }, [dispatch, index, dataBounds, palettes]);
  (0, _useUpdateEffect.default)(() => {
    if (!Number.isNaN(colorRange[accessor]) && colorRange[accessor] !== localValue) {
      setLocalValue(colorRange[accessor]);
    }
  }, [localValue, colorRange, accessor]);
  const selectNewColorText = _i18n.i18n.translate('coloring.dynamicColoring.customPalette.selectNewColor', {
    defaultMessage: 'Select a new color'
  });
  const styles = (0, _react.useMemo)(() => (0, _react2.css)`
      display: block;
      min-width: ${euiTheme.size.xl};
      text-align: center;
    `, [euiTheme.size.xl]);
  const autoBoundInfo = (0, _utils.getAutoBoundInformation)({
    isPercentage: rangeType === 'percent',
    isUpper: isLast,
    isAuto: mode === 'auto'
  });
  return /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    alignItems: "center",
    gutterSize: "s",
    wrap: false,
    responsive: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false,
    css: isLast ? styles : null
  }, !isLast ? /*#__PURE__*/_react.default.createElement(_eui.EuiColorPicker, {
    onChange: onUpdateColor,
    button: isColorValid ? /*#__PURE__*/_react.default.createElement(_eui.EuiColorPickerSwatch, {
      color: colorRange.color,
      "aria-label": selectNewColorText,
      style: {
        width: euiTheme.size.xl,
        height: euiTheme.size.xl
      }
    }) : /*#__PURE__*/_react.default.createElement(_eui.EuiButtonIcon, {
      color: "danger",
      iconType: "stopSlash",
      iconSize: "l",
      "aria-label": selectNewColorText
    }),
    secondaryInputDisplay: "top",
    color: colorRange.color,
    showAlpha: true,
    onFocus: () => setPopoverInFocus(true),
    onBlur: () => {
      setPopoverInFocus(false);
    },
    isInvalid: !isColorValid
  }) : /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
    type: _related.RelatedIcon,
    size: "m",
    color: euiTheme.colors.disabled
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: true
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFieldNumber, {
    compressed: true,
    fullWidth: true,
    isInvalid: !isValid,
    value: mode !== 'auto' && localValue !== undefined && isFinite(localValue) ? localValue : '',
    disabled: isDisabled,
    onChange: onValueChange,
    placeholder: mode === 'auto' ? autoBoundInfo.representation : '',
    append: getAppend(rangeType, mode),
    onBlur: onLeaveFocus,
    "data-test-subj": `lnsPalettePanel_dynamicColoring_range_value_${index}`,
    prepend: /*#__PURE__*/_react.default.createElement("span", {
      className: "euiFormLabel"
    }, isLast ? '\u2264' : '\u2265'),
    "aria-label": _i18n.i18n.translate('coloring.dynamicColoring.customPalette.rangeAriaLabel', {
      defaultMessage: 'Range {index}',
      values: {
        index: index + 1
      }
    }),
    step: "any"
  })), ActionButton ? /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(ActionButton, {
    index: index,
    continuity: continuity,
    rangeType: rangeType,
    colorRanges: colorRanges,
    dispatch: dispatch,
    tooltipContent: autoBoundInfo.actionDescription,
    iconFactory: autoBoundInfo.icon,
    accessor: accessor
  })) : null);
}