"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DateTimeDecorator = exports["default"] = void 0;

var _jsxRuntime = require("react/jsx-runtime");

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");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/*
 * 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 = (0, _hoc["default"])(function (config, Wrapped) {
  var _class, _temp;

  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 = (_temp = _class = /*#__PURE__*/function (_Component) {
    _inherits(Decorator, _Component);

    var _super = _createSuper(Decorator);

    function Decorator(props) {
      var _this;

      _classCallCheck(this, Decorator);

      _this = _super.call(this, props);

      _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(_assertThisInitialized(_this), handlers[name]);
        });
      }

      return _this;
    }

    _createClass(Decorator, [{
      key: "toIDate",

      /**
       * Converts a Date to an IDate
       *
       * @param	{Date}	time	Date object
       *
       * @returns	{IDate}			ilib Date object
       */
      value: function toIDate(time) {
        if (time && this.props.locale) {
          return (0, _DateFactory["default"])({
            unixtime: time,
            timezone: 'local'
          });
        }
      }
      /**
       * Updates the internal value in state
       *
       * @param	{IDate}		value	ilib Date object
       *
       * @returns {Number}			Updated internal value
       */

    }, {
      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;
      }
    }]);

    return Decorator;
  }(_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)
  }, _temp);
  return (0, _I18nDecorator.I18nContextDecorator)({
    rtlProp: 'rtl',
    localeProp: 'locale'
  }, (0, _Changeable["default"])(Decorator));
});
exports.DateTimeDecorator = DateTimeDecorator;
var _default = DateTimeDecorator;
exports["default"] = _default;