"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ButtonPayment = 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 _ButtonPayment = require("./ButtonPayment.constants");
var _ButtonPayment2 = require("./ButtonPayment.l10n");
var style = _interopRequireWildcard(require("./ButtonPayment.module.css"));
var _Form = require("./components/Form");
var _helpers = require("./helpers");
var _Payment = require("../Payment");
const _excluded = ["currencyDecimals", "gateway", "provider"],
  _excluded2 = ["id"],
  _excluded3 = ["children", "config", "dataSource", "hotel", "info", "methods", "promise", "tracking", "onError", "onPress", "onSuccess"];
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 {
  AMAZON_PAY,
  APLAZAME,
  CARD,
  PCIPROXY,
  TPV
} = _Payment.PAYMENT_METHOD;
const {
  ADDON,
  ADYEN,
  CHECKOUT,
  HOTELPAY,
  LINKAGEPAY,
  NUVEI,
  OPENPAY,
  PAYBYRD,
  PAYCOMET,
  STRIPE
} = _Payment.PAYMENT_PROVIDER;
const PROVIDERS_WITH_MODAL = [ADDON, ADYEN, CHECKOUT, NUVEI, PAYCOMET];
const ButtonPayment = _ref => {
  var _methods$method2, _methods$method2$conf, _methods$method3, _methods$method4;
  let {
      children,
      config: {
        currencyDecimals,
        gateway,
        provider
      } = {},
      dataSource = {},
      hotel: {
        id
      } = {},
      info = {},
      methods = [],
      promise = () => new Promise(resolve => resolve({})),
      tracking,
      onError = () => {},
      onPress = () => {},
      onSuccess = () => {}
    } = _ref,
    config = _objectWithoutProperties(_ref.config, _excluded),
    propHotel = _objectWithoutProperties(_ref.hotel, _excluded2),
    others = _objectWithoutProperties(_ref, _excluded3);
  const {
    locale,
    translate
  } = (0, _locale.useLocale)();
  const {
    value: {
      forwarder,
      payment = dataSource || {},
      hotel = propHotel || {},
      urlParams
    } = {}
  } = (0, _dataSources.useStore)();
  const [modal, setModal] = (0, _react.useState)(false);
  const [response, setResponse] = (0, _react.useState)();
  const handleClose = () => {
    setModal(false);
    onError();
  };
  (0, _react.useEffect)(() => {
    if (provider === LINKAGEPAY) return;
    const {
      error,
      orderReference,
      token,
      transactionId
    } = payment;
    if (orderReference || token || transactionId) handleSuccess();else if (error) onError(error);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [payment]);
  const handlePress = async () => {
    var _methods$method;
    if (onPress() === false) return;
    const {
      method
    } = payment || {};
    if ([AMAZON_PAY, PCIPROXY].includes(method) || method === TPV && provider === OPENPAY) {
      return document.dispatchEvent(new window.Event(_ButtonPayment.EVENT.CTA_PRESS));
    }
    const requireCardValidation = [CARD, PCIPROXY].includes(method) && cardValidation;
    const withModal = (PROVIDERS_WITH_MODAL.includes(provider) || ((_methods$method = methods[method]) === null || _methods$method === void 0 ? void 0 : _methods$method.modal)) && (method === TPV || requireCardValidation);
    const response = !withModal || isModalResponse || method === APLAZAME ? await promise(promiseData).catch(onError) : true;
    if (!response) return;
    if (withModal || response.type === _ButtonPayment.TYPE.SUBMIT) setResponse(response);
    if (withModal) {
      try {
        _dataSources.Event.publish(_ButtonPayment.EVENT.OPEN_MODAL);
      } catch (_unused) {
        //123 compare is failed when capture this event.
      }
      setModal(true);
    } else if (method === APLAZAME || method === TPV && provider === LINKAGEPAY) {
      document.dispatchEvent(new CustomEvent(_ButtonPayment.EVENT.SERVICE_RESPONSE, {
        detail: _objectSpread(_objectSpread({}, response), {}, {
          publicKey
        })
      }));
    } else {
      const url = (0, _helpers.getUrl)(_objectSpread(_objectSpread({}, hotel), {}, {
        id,
        forwarder,
        locale,
        response,
        tracking,
        urlParams
      }));
      if (url) window.location.href = url;
    }
  };
  const handleSuccess = async value => {
    setModal(false);
    const response = await promise(_objectSpread(_objectSpread({}, value), promiseData)).catch(onError);
    if (!response) return;
    if (payment.method === AMAZON_PAY) return document.dispatchEvent(new CustomEvent(_ButtonPayment.EVENT.AMAZON_PAY_RESPONSE, {
      detail: {
        response
      }
    }));
    if (response) {
      const url = (0, _helpers.getUrl)(_objectSpread(_objectSpread({}, hotel), {}, {
        id,
        forwarder,
        locale,
        response,
        tracking,
        urlParams
      }));
      if (url) {
        onSuccess(url);
        window.location.href = url;
      }
    }
  };
  const {
    method
  } = payment || {};
  const {
    cardValidation
  } = info || {};
  const publicKey = ((_methods$method2 = methods[method]) === null || _methods$method2 === void 0 ? void 0 : (_methods$method2$conf = _methods$method2.config) === null || _methods$method2$conf === void 0 ? void 0 : _methods$method2$conf.publicKey) || (config === null || config === void 0 ? void 0 : config.publicKey);
  const component = (0, _helpers.getComponent)({
    cardValidation,
    method,
    methodConfig: methods[method],
    provider
  });
  const isModalResponse = [ADDON, ADYEN, HOTELPAY, NUVEI, PAYBYRD, PAYCOMET].includes(provider) || provider === STRIPE && ((_methods$method3 = methods[method]) === null || _methods$method3 === void 0 ? void 0 : _methods$method3.modal);
  const promiseData = gateway ? {
    gateway
  } : {};
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ui.Button, _extends({}, others, {
    onPress: handlePress
  }), children || translate(_ButtonPayment2.L10N.ACTION_BOOK_NOW)), (response === null || response === void 0 ? void 0 : response.type) === _ButtonPayment.TYPE.SUBMIT && /*#__PURE__*/_react.default.createElement(_Form.Form, response), /*#__PURE__*/_react.default.createElement(_ui.Modal, {
    portal: isModalResponse,
    title: method,
    visible: modal,
    onClose: handleClose
  }, component && /*#__PURE__*/_react.default.createElement(component, _objectSpread(_objectSpread(_objectSpread({}, config), (_methods$method4 = methods[method]) === null || _methods$method4 === void 0 ? void 0 : _methods$method4.prepayment), {}, {
    currencyDecimals,
    info,
    method,
    provider,
    publicKey,
    response,
    onClose: handleClose,
    onError,
    onSuccess: handleSuccess,
    className: style.modalContent
  }))));
};
exports.ButtonPayment = ButtonPayment;
ButtonPayment.displayName = 'Mirai:Core:ButtonPayment';
ButtonPayment.propTypes = {
  children: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.node]),
  config: _propTypes.default.shape({
    currencyDecimals: _propTypes.default.number,
    gateway: _propTypes.default.object,
    provider: _propTypes.default.oneOf(Object.values(_Payment.PAYMENT_PROVIDER)),
    publicKey: _propTypes.default.string,
    showCVV: _propTypes.default.bool
  }),
  dataSource: _propTypes.default.shape({
    method: _propTypes.default.oneOf(Object.values(_Payment.PAYMENT_METHOD))
  }),
  hotel: _propTypes.default.shape({
    id: _propTypes.default.string,
    url: _propTypes.default.string
  }),
  info: _propTypes.default.shape({
    amount: _propTypes.default.number,
    cardValidation: _propTypes.default.bool,
    date: _propTypes.default.instanceOf(Date)
  }),
  methods: _propTypes.default.array,
  promise: _propTypes.default.func,
  tracking: _propTypes.default.string,
  onError: _propTypes.default.func,
  onPress: _propTypes.default.func,
  onSuccess: _propTypes.default.func
};
//# sourceMappingURL=ButtonPayment.js.map