"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "EuiQuickSelect", {
  enumerable: true,
  get: function get() {
    return _quick_select.EuiQuickSelect;
  }
});
exports.OuiQuickSelect = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _moment = _interopRequireDefault(require("moment"));
var _datemath = _interopRequireDefault(require("@opensearch/datemath"));
var _services = require("../../../../services");
var _button = require("../../../button");
var _flex = require("../../../flex");
var _spacer = require("../../../spacer");
var _form = require("../../../form");
var _tool_tip = require("../../../tool_tip");
var _horizontal_rule = require("../../../horizontal_rule");
var _i18n = require("../../../i18n");
var _time_units = require("../time_units");
var _accessibility = require("../../../accessibility");
var _common = require("../../../common");
var _quick_select_utils = require("./quick_select_utils");
var _quick_select = require("../../../../eui_components/date_picker/super_date_picker/quick_select_popover/quick_select");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = _getPrototypeOf(t); if (r) { var s = _getPrototypeOf(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return _possibleConstructorReturn(this, e); }; }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */ /*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var LAST = 'last';
var NEXT = 'next';
var timeTenseOptions = [{
  value: LAST,
  text: 'Last'
}, {
  value: NEXT,
  text: 'Next'
}];
var timeUnitsOptions = (0, _common.keysOf)(_time_units.timeUnits).map(function (key) {
  return {
    value: key,
    text: "".concat(_time_units.timeUnits[key], "s")
  };
});
var OuiQuickSelect = /*#__PURE__*/function (_Component) {
  _inherits(OuiQuickSelect, _Component);
  var _super = _createSuper(OuiQuickSelect);
  function OuiQuickSelect(props) {
    var _this;
    _classCallCheck(this, OuiQuickSelect);
    _this = _super.call(this, props);
    _defineProperty(_assertThisInitialized(_this), "generateId", (0, _services.htmlIdGenerator)());
    _defineProperty(_assertThisInitialized(_this), "onTimeTenseChange", function (event) {
      _this.setState({
        timeTense: event.target.value
      });
    });
    _defineProperty(_assertThisInitialized(_this), "onTimeValueChange", function (event) {
      var sanitizedValue = parseInt(event.target.value, 10);
      _this.setState({
        timeValue: isNaN(sanitizedValue) ? 0 : sanitizedValue
      });
    });
    _defineProperty(_assertThisInitialized(_this), "onTimeUnitsChange", function (event) {
      _this.setState({
        timeUnits: event.target.value
      });
    });
    _defineProperty(_assertThisInitialized(_this), "handleKeyDown", function (_ref) {
      var key = _ref.key;
      if (key === 'Enter') {
        _this.applyQuickSelect();
      }
    });
    _defineProperty(_assertThisInitialized(_this), "applyQuickSelect", function () {
      var _this$state = _this.state,
        timeTense = _this$state.timeTense,
        timeValue = _this$state.timeValue,
        timeUnits = _this$state.timeUnits;
      if (timeTense === NEXT) {
        _this.props.applyTime({
          start: 'now',
          end: "now+".concat(timeValue).concat(timeUnits),
          quickSelect: _objectSpread({}, _this.state)
        });
        return;
      }
      _this.props.applyTime({
        start: "now-".concat(timeValue).concat(timeUnits),
        end: 'now',
        quickSelect: _objectSpread({}, _this.state)
      });
    });
    _defineProperty(_assertThisInitialized(_this), "getBounds", function () {
      var startMoment = _datemath.default.parse(_this.props.start);
      var endMoment = _datemath.default.parse(_this.props.end, {
        roundUp: true
      });
      return {
        min: startMoment && startMoment.isValid() ? startMoment : (0, _moment.default)().subtract(15, 'minute'),
        max: endMoment && endMoment.isValid() ? endMoment : (0, _moment.default)()
      };
    });
    _defineProperty(_assertThisInitialized(_this), "stepForward", function () {
      var _this$getBounds = _this.getBounds(),
        min = _this$getBounds.min,
        max = _this$getBounds.max;
      var diff = max.diff(min);
      _this.props.applyTime({
        start: (0, _moment.default)(max).add(1, 'ms').toISOString(),
        end: (0, _moment.default)(max).add(diff + 1, 'ms').toISOString(),
        keepPopoverOpen: true
      });
    });
    _defineProperty(_assertThisInitialized(_this), "stepBackward", function () {
      var _this$getBounds2 = _this.getBounds(),
        min = _this$getBounds2.min,
        max = _this$getBounds2.max;
      var diff = max.diff(min);
      _this.props.applyTime({
        start: (0, _moment.default)(min).subtract(diff + 1, 'ms').toISOString(),
        end: (0, _moment.default)(min).subtract(1, 'ms').toISOString(),
        keepPopoverOpen: true
      });
    });
    var _parseTimeParts = (0, _quick_select_utils.parseTimeParts)(props.start, props.end),
      timeTenseDefault = _parseTimeParts.timeTense,
      timeUnitsDefault = _parseTimeParts.timeUnits,
      timeValueDefault = _parseTimeParts.timeValue;
    _this.state = {
      timeTense: props.prevQuickSelect && props.prevQuickSelect.timeTense ? props.prevQuickSelect.timeTense : timeTenseDefault,
      timeValue: props.prevQuickSelect && props.prevQuickSelect.timeValue ? props.prevQuickSelect.timeValue : timeValueDefault,
      timeUnits: props.prevQuickSelect && props.prevQuickSelect.timeUnits ? props.prevQuickSelect.timeUnits : timeUnitsDefault
    };
    return _this;
  }
  _createClass(OuiQuickSelect, [{
    key: "render",
    value: function render() {
      var _this2 = this;
      var _this$state2 = this.state,
        timeTense = _this$state2.timeTense,
        timeValue = _this$state2.timeValue,
        timeUnits = _this$state2.timeUnits;
      var timeSelectionId = this.generateId();
      var legendId = this.generateId();
      var matchedTimeUnit = timeUnitsOptions.find(function (_ref2) {
        var value = _ref2.value;
        return value === timeUnits;
      });
      var timeUnit = matchedTimeUnit ? matchedTimeUnit.text : '';
      return /*#__PURE__*/_react.default.createElement("fieldset", null, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiQuickSelect.legendText",
        default: "Quick select a time range"
      }, function (legendText) {
        return (
          /*#__PURE__*/
          // Legend needs to be the first thing in a fieldset, but we want the visible title within the flex.
          // So we hide it, but allow screen readers to see it
          _react.default.createElement(_accessibility.OuiScreenReaderOnly, null, /*#__PURE__*/_react.default.createElement("legend", {
            id: legendId,
            className: "ouiFormLabel"
          }, legendText))
        );
      }), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexGroup, {
        responsive: false,
        alignItems: "center",
        justifyContent: "spaceBetween",
        gutterSize: "s"
      }, /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiQuickSelect.quickSelectTitle",
        default: "Quick select"
      }, function (quickSelectTitle) {
        return /*#__PURE__*/_react.default.createElement("div", {
          "aria-hidden": true,
          className: "ouiFormLabel"
        }, quickSelectTitle);
      })), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_flex.OuiFlexGroup, {
        alignItems: "center",
        gutterSize: "s",
        responsive: false
      }, /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiQuickSelect.previousLabel",
        default: "Previous time window"
      }, function (previousLabel) {
        return /*#__PURE__*/_react.default.createElement(_tool_tip.OuiToolTip, {
          content: previousLabel
        }, /*#__PURE__*/_react.default.createElement(_button.OuiButtonIcon, {
          "aria-label": previousLabel,
          iconType: "arrowLeft",
          onClick: _this2.stepBackward
        }));
      })), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiQuickSelect.nextLabel",
        default: "Next time window"
      }, function (nextLabel) {
        return /*#__PURE__*/_react.default.createElement(_tool_tip.OuiToolTip, {
          content: nextLabel
        }, /*#__PURE__*/_react.default.createElement(_button.OuiButtonIcon, {
          "aria-label": nextLabel,
          iconType: "arrowRight",
          onClick: _this2.stepForward
        }));
      }))))), /*#__PURE__*/_react.default.createElement(_spacer.OuiSpacer, {
        size: "s"
      }), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexGroup, {
        gutterSize: "s",
        responsive: false
      }, /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiQuickSelect.tenseLabel",
        default: "Time tense"
      }, function (tenseLabel) {
        return /*#__PURE__*/_react.default.createElement(_form.OuiSelect, {
          compressed: true,
          onKeyDown: _this2.handleKeyDown,
          "aria-label": tenseLabel,
          "aria-describedby": "".concat(timeSelectionId, " ").concat(legendId),
          value: timeTense,
          options: timeTenseOptions,
          onChange: _this2.onTimeTenseChange
        });
      })), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiQuickSelect.valueLabel",
        default: "Time value"
      }, function (valueLabel) {
        return /*#__PURE__*/_react.default.createElement(_form.OuiFieldNumber, {
          compressed: true,
          onKeyDown: _this2.handleKeyDown,
          "aria-describedby": "".concat(timeSelectionId, " ").concat(legendId),
          "aria-label": valueLabel,
          value: timeValue,
          onChange: _this2.onTimeValueChange
        });
      })), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiQuickSelect.unitLabel",
        default: "Time unit"
      }, function (unitLabel) {
        return /*#__PURE__*/_react.default.createElement(_form.OuiSelect, {
          compressed: true,
          onKeyDown: _this2.handleKeyDown,
          "aria-label": unitLabel,
          "aria-describedby": "".concat(timeSelectionId, " ").concat(legendId),
          value: timeUnits,
          options: timeUnitsOptions,
          onChange: _this2.onTimeUnitsChange
        });
      })), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_button.OuiButton, {
        "aria-describedby": "".concat(timeSelectionId, " ").concat(legendId),
        className: "ouiQuickSelect__applyButton",
        size: "s",
        onClick: this.applyQuickSelect,
        disabled: timeValue <= 0
      }, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiQuickSelect.applyButton",
        default: "Apply"
      })))), /*#__PURE__*/_react.default.createElement(_horizontal_rule.OuiHorizontalRule, {
        margin: "s"
      }), /*#__PURE__*/_react.default.createElement(_accessibility.OuiScreenReaderOnly, null, /*#__PURE__*/_react.default.createElement("p", {
        id: timeSelectionId
      }, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiQuickSelect.fullDescription",
        default: "Currently set to {timeTense} {timeValue} {timeUnit}.",
        values: {
          timeTense: timeTense,
          timeValue: timeValue,
          timeUnit: timeUnit
        }
      }))));
    }
  }]);
  return OuiQuickSelect;
}(_react.Component);
/* OUI -> EUI Aliases: Build-Time */
exports.OuiQuickSelect = OuiQuickSelect;
OuiQuickSelect.propTypes = {
  applyTime: _propTypes.default.func.isRequired,
  start: _propTypes.default.string.isRequired,
  end: _propTypes.default.string.isRequired,
  prevQuickSelect: _propTypes.default.shape({
    timeTense: _propTypes.default.string.isRequired,
    timeValue: _propTypes.default.number.isRequired,
    timeUnits: _propTypes.default.oneOf(["s", "m", "h", "d", "w", "M", "y"]).isRequired
  })
};
/* OUI -> EUI Aliases: Build-Time */