"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Modal = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _BookingModal = require("./Booking.Modal.actions");
var _Core = require("../../../Core.constants");
var _helpers = require("../../helpers");
var _Booking = require("../Booking.constants");
var _Booking2 = require("../Booking.l10n");
var style = _interopRequireWildcard(require("../Booking.module.css"));
const _excluded = ["id", "pinCode", "token"],
  _excluded2 = ["action", "dataSource", "onChange", "onClose"];
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (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 (const 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 _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
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 _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 _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
const ACTION_VALUES = Object.values(_Booking.ACTION);
const Modal = _ref => {
  var _config$getFormProps;
  let {
      action,
      dataSource: {
        id,
        pinCode,
        token
      } = {},
      onChange = () => {},
      onClose
    } = _ref,
    dataSource = _objectWithoutProperties(_ref.dataSource, _excluded),
    others = _objectWithoutProperties(_ref, _excluded2);
  const {
    translate
  } = (0, _locale.useLocale)();
  const {
    value: {
      urlParams: {
        idHotel
      } = {}
    }
  } = (0, _dataSources.useStore)();
  const [busy, setBusy] = (0, _react.useState)();
  const [error, setError] = (0, _react.useState)();
  const [form, setForm] = (0, _react.useState)({});
  const [visible, setVisible] = (0, _react.useState)(false);
  const config = (0, _BookingModal.getModalActionConfig)(action);
  (0, _react.useEffect)(() => {
    if (action) return setVisible(true);
    setForm({});
  }, [action]);
  const handleChange = (0, _react.useCallback)(next => {
    setForm(previous => _objectSpread(_objectSpread({}, previous), next));
  }, []);
  const handleError = error => {
    setError(error);
  };
  const handleSubmit = async () => {
    setBusy(true);
    const response = await config.request({
      form,
      id,
      idHotel,
      pinCode,
      token
    }).catch(error => {
      const isWarning = (error === null || error === void 0 ? void 0 : error.code) === 404 && config.warningOn404;
      _dataSources.Event.publish(_helpers.EVENT.NOTIFICATION, {
        error: !isWarning,
        warning: isWarning,
        defaultMessage: translate(isWarning ? _Booking2.L10N.NOTIFICATION_WARNING_NO_AVAILABILITY : _Booking2.L10N.NOTIFICATION_ERROR[_Core.ERROR.UNKNOWN], {
          checkIn: (0, _locale.dateFormat)((0, _locale.parseDate)(form === null || form === void 0 ? void 0 : form.checkIn), _Booking.FORMAT_DATE),
          checkOut: (0, _locale.dateFormat)((0, _locale.parseDate)(form === null || form === void 0 ? void 0 : form.checkOut), _Booking.FORMAT_DATE)
        })
      });
    });
    setBusy(false);
    if (!response) return;
    _dataSources.Event.publish(_helpers.EVENT.NOTIFICATION, _objectSpread({
      success: true
    }, config.successL10N));
    handleClose();
    onChange({
      response,
      state: config.state
    });
  };
  const handleClose = nextAction => {
    const {
      motionExpand = '0.3s'
    } = _ui.Theme.get();
    const action = ACTION_VALUES.includes(nextAction) ? nextAction : undefined;
    setVisible(false);
    setTimeout(() => onClose(action), parseFloat(motionExpand.replace('s')) * 1000);
  };
  return /*#__PURE__*/_react.default.createElement(_ui.Modal, _extends({}, others, {
    fit: config.fit,
    preventDefault: false,
    title: translate(config.titleL10N),
    visible: visible,
    onClose: handleClose,
    className: (0, _ui.styles)(config.className, others.className)
  }), /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: (0, _ui.styles)(style.modal, config.editLayout && style.edit)
  }, /*#__PURE__*/_react.default.createElement(config.Form, _objectSpread(_objectSpread({
    dataSource,
    form
  }, (_config$getFormProps = config.getFormProps) === null || _config$getFormProps === void 0 ? void 0 : _config$getFormProps.call(config, others)), {}, {
    onChange: handleChange,
    onError: handleError
  })), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true,
    className: (0, _ui.styles)(style.buttons, config.editLayout && style.edit)
  }, /*#__PURE__*/_react.default.createElement(_ui.Button, {
    large: true,
    secondary: true,
    wide: true,
    onPress: () => handleClose(config.backAction),
    testId: "cancel-button"
  }, translate(_Booking2.L10N.ACTION_BACK)), /*#__PURE__*/_react.default.createElement(_ui.Button, {
    busy: busy,
    disabled: config.disableSubmitOnError && !!error,
    large: true,
    wide: true,
    onPress: handleSubmit,
    testId: "submit-button"
  }, translate(config.submitL10N)))));
};
exports.Modal = Modal;
Modal.displayName = 'Mirai:Core:Booking:Modal';
Modal.propTypes = {
  action: _propTypes.default.oneOf(Object.values(_Booking.ACTION)),
  dataSource: _propTypes.default.shape({
    id: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.number]),
    pinCode: _propTypes.default.number,
    token: _propTypes.default.string
  }),
  onChange: _propTypes.default.func,
  onClose: _propTypes.default.func
};
//# sourceMappingURL=Booking.Modal.js.map