"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.DateTimeDecorator = void 0;
var _handle = require("@enact/core/handle");
var _hoc = _interopRequireDefault(require("@enact/core/hoc"));
var _util = require("@enact/core/util");
var _I18nDecorator = require("@enact/i18n/I18nDecorator");
var _Changeable = _interopRequireDefault(require("@enact/ui/Changeable"));
var _DateFactory = _interopRequireDefault(require("ilib/lib/DateFactory"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = require("react");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
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 _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 _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 _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); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, 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 _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); } /**
 * Exports the {@link agate/internal/DateTimeDecorator.DateTimeDecorator} higher-order component
 *
 * @module agate/internal/DateTimeDecorator
 * @private
 */ /*
 * Converts a JavaScript Date to unix time
 *
 * @param	{Date}	date	A Date to convert
 *
 * @returns	{undefined}
 */
var toTime = function toTime(date) {
  return date && typeof date.getTime === 'function' ? date.getTime() : null;
};

/**
 * {@link agate/internal/DateTimeDecorator.DateTimeDecorator} provides common behavior for
 * {@link agate/DatePicker.DatePicker} and {@link agate/TimePicker.TimePicker}.
 *
 * @class DateTimeDecorator
 * @hoc
 * @memberof agate/internal/DateTimeDecorator
 * @mixes ui/Changeable.Changeable
 * @private
 */
var DateTimeDecorator = exports.DateTimeDecorator = (0, _hoc["default"])(function (config, Wrapped) {
  var _Class;
  var customProps = config.customProps,
    defaultOrder = config.defaultOrder,
    handlers = config.handlers,
    i18n = config.i18n;
  var memoizedI18nConfig = (0, _util.memoize)(function /* locale */
  () {
    // Guard for isomorphic builds
    if (typeof window !== 'undefined' && i18n) {
      return i18n();
    }
    return null;
  });
  var Decorator = (_Class = /*#__PURE__*/function (_Component) {
    function Decorator(props) {
      var _this;
      _classCallCheck(this, Decorator);
      _this = _callSuper(this, Decorator, [props]);
      /**
       * Updates the internal value in state
       *
       * @param	{IDate}		value	ilib Date object
       *
       * @returns {Number}			Updated internal value
       */
      _this.updateValue = function (value, reverseTransition) {
        var day = value.day,
          month = value.month,
          year = value.year;
        var maxDays = value.cal.getMonLength(month, year);
        value.day = day <= maxDays ? day : maxDays;
        var prevValue = _this.toIDate(_this.state.value);
        var prevMaxDays = prevValue.cal.getMonLength(prevValue.month, prevValue.year);
        var date = (0, _DateFactory["default"])(value);
        var newValue = date.getTimeExtended();
        var changed = _this.props.value == null || _this.props.value !== newValue;
        if (prevMaxDays === maxDays) {
          _this.setState({
            value: newValue,
            dayReverseTransition: reverseTransition
          });
        } else if (prevValue.day === prevMaxDays || prevValue.day !== prevMaxDays && prevValue.day > maxDays) {
          _this.setState({
            value: newValue,
            dayReverseTransition: true
          });
        } else if (prevValue.day !== prevMaxDays && prevValue.day <= maxDays) {
          _this.setState({
            value: newValue,
            dayReverseTransition: false
          });
        }
        if (changed) {
          _this.emitChange(date);
        }
        return newValue;
      };
      _this.emitChange = function (date) {
        (0, _handle.forward)('onChange', {
          value: date ? date.getJSDate() : null
        }, _this.props);
      };
      _this.handlePickerChange = function (handler, ev) {
        var value = _this.toIDate(_this.state.value);
        handler(ev, value, memoizedI18nConfig(_this.props.locale));
        _this.updateValue(value, ev.reverseTransition);
      };
      _this.handleCancel = function () {
        var _this$state = _this.state,
          initialValue = _this$state.initialValue,
          value = _this$state.value;

        // if we're cancelling, reset our state and emit an onChange with the initial value
        _this.setState({
          value: null,
          initialValue: null,
          pickerValue: value
        });
        if (initialValue !== value) {
          _this.emitChange(_this.toIDate(initialValue));
        }
      };
      _this.state = {
        initialValue: null,
        dayReverseTransition: null,
        value: null
      };
      var _newValue = toTime(_this.props.value);
      var _value = _newValue || Date.now();

      // if no value was provided, we need to emit the onChange event for the generated value
      if (!_newValue) {
        _this.emitChange(_this.toIDate(_value));
      }
      _this.handlers = {};
      if (handlers) {
        Object.keys(handlers).forEach(function (name) {
          _this.handlers[name] = _this.handlePickerChange.bind(_this, handlers[name]);
        });
      }
      return _this;
    }
    _inherits(Decorator, _Component);
    return _createClass(Decorator, [{
      key: "toIDate",
      value:
      /**
       * Converts a Date to an IDate
       *
       * @param	{Date}	time	Date object
       *
       * @returns	{IDate}			ilib Date object
       */
      function toIDate(time) {
        if (time && this.props.locale) {
          return (0, _DateFactory["default"])({
            unixtime: time,
            timezone: 'local'
          });
        }
      }
    }, {
      key: "render",
      value: function render() {
        var value = this.toIDate(this.state.value);
        // pickerValue is only set when cancelling to prevent the unexpected changing of the
        // picker values before closing.
        var pickerValue = this.state.pickerValue ? this.toIDate(this.state.pickerValue) : value;
        var props = null;
        var order = defaultOrder;
        var i18nConfig = memoizedI18nConfig(this.props.locale);
        if (i18nConfig) {
          props = customProps(i18nConfig, pickerValue, this.state.dayReverseTransition, this.props);
          order = i18nConfig.order;
        }
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, this.props), props), this.handlers), {}, {
          order: order,
          value: value
        }));
      }
    }], [{
      key: "getDerivedStateFromProps",
      value: function getDerivedStateFromProps(props, state) {
        var value = toTime(props.value);
        if (!props.disabled && state.initialValue == null && state.value == null) {
          return {
            initialValue: value,
            value: value || Date.now()
          };
        } else if (state.value !== value) {
          // always respect a value change from props
          return {
            value: value
          };
        }
        return null;
      }
    }]);
  }(_react.Component), _Class.displayName = 'DateTimeDecorator', _Class.propTypes = /** @lends agate/internal/DateTimeDecorator.DateTimeDecorator.prototype */{
    /**
     * The current locale as a
     * {@link https://tools.ietf.org/html/rfc5646|BCP 47 language tag}.
     *
     * @type {String}
     * @public
     */
    locale: _propTypes["default"].string,
    /**
     * Handler for `onChange` events
     *
     * @type {Function}
     * @public
     */
    onChange: _propTypes["default"].func,
    /**
     * The selected date
     *
     * @type {Date}
     * @public
     */
    value: _propTypes["default"].instanceOf(Date)
  }, _Class);
  return (0, _I18nDecorator.I18nContextDecorator)({
    rtlProp: 'rtl',
    localeProp: 'locale'
  }, (0, _Changeable["default"])(Decorator));
});
var _default = exports["default"] = DateTimeDecorator;