"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FormShift4 = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = require("react");
var _FormShift = require("./FormShift4.constants");
var _loadScript = require("../../../../../helpers/loadScript");
var _helpers = require("../../../../helpers");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const FormShift4 = _ref => {
  let {
    response,
    onClose = () => {}
  } = _ref;
  const {
    language
  } = (0, _locale.useLocale)();
  const [ready, setReady] = (0, _react.useState)();
  (0, _react.useEffect)(() => {
    (async () => {
      await (0, _loadScript.loadScript)({
        async: false,
        domain: 'payments',
        id: 'shift4Script',
        src: _FormShift.SCRIPT_URL,
        onLoad: handleLoad
      });
    })();
  }, [response]);
  (0, _react.useEffect)(() => {
    if (!response || !ready) return;
    const {
      Shift4Checkout
    } = window || {};
    const {
      configuration: {
        clientSecret,
        email,
        publicKey
      } = {}
    } = response;
    Shift4Checkout.key = publicKey;
    Shift4Checkout.success = handleSuccess;
    Shift4Checkout.error = handleError;
    Shift4Checkout.close = onClose;
    Shift4Checkout.open({
      clientSecret,
      email,
      locale: _FormShift.SUPPORTED_LANGUAGES.includes(language) ? language : _FormShift.DEFAULT_LANGUAGE
    });

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ready, response]);
  const handleError = errorMessage => {
    _dataSources.Event.publish(_helpers.EVENT.NOTIFICATION, {
      error: true,
      defaultMessage: errorMessage
    });
  };
  const handleLoad = async () => {
    setReady(true);
  };
  const handleSuccess = result => {
    if (!result) return;
    const {
      configuration: {
        paymentTransactionId,
        returnUrl
      } = {}
    } = response;
    const url = new URL(returnUrl);
    paymentTransactionId && url.searchParams.append('paymentTransactionId', paymentTransactionId);
    window.location.href = url.toString();
  };
  return null;
};
exports.FormShift4 = FormShift4;
FormShift4.displayName = 'Mirai:Payments:ButtonPayment:FormShift4';
FormShift4.propTypes = {
  response: _propTypes.default.object,
  onClose: _propTypes.default.func
};
//# sourceMappingURL=FormShift4.js.map