"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FormAdyen = void 0;
var _locale = require("@mirai/locale");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _FormAdyen = require("./FormAdyen.constants");
var _FormAdyen2 = require("./FormAdyen.l10n");
var style = _interopRequireWildcard(require("./FormAdyen.module.css"));
var _loadScript = require("../../../../../helpers/loadScript");
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 _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
const FormAdyen = _ref => {
  let response = _ref.response;
  const _useLocale = (0, _locale.useLocale)(),
    translate = _useLocale.translate;
  const _useState = (0, _react.useState)(),
    _useState2 = _slicedToArray(_useState, 2),
    error = _useState2[0],
    setError = _useState2[1];
  const _useState3 = (0, _react.useState)(),
    _useState4 = _slicedToArray(_useState3, 2),
    ready = _useState4[0],
    setReady = _useState4[1];
  const refContainer = (0, _react.useRef)();
  (0, _react.useEffect)(() => {
    const _ref2 = response || {},
      _ref2$configuration = _ref2.configuration,
      _ref2$configuration2 = _ref2$configuration === void 0 ? {} : _ref2$configuration,
      _ref2$configuration2$ = _ref2$configuration2.environment,
      environment = _ref2$configuration2$ === void 0 ? 'test' : _ref2$configuration2$;
    const url = _FormAdyen.URL.replace('{environment}', environment);
    const exists = document.getElementById('addyenCSS');
    if (!exists) {
      const css = document.createElement('link');
      css.crossOrigin = 'anonymous';
      css.id = 'addyenCSS';
      css.integrity = 'sha384-pC2TKxh6gMtWIUiXzlw5Jnq9ZtnyuPT0ymaHY6skdegLVNDMNiiQ7/NFixA87/Wb';
      css.rel = 'stylesheet';
      css.href = "".concat(url, "adyen.css");
      document.head.appendChild(css);
    }
    let remove;
    (async () => {
      remove = await (0, _loadScript.loadScript)({
        async: false,
        crossOrigin: 'anonymous',
        domain: 'payments',
        id: 'addyenScript',
        integrity: 'sha384-PpkKjJdtlCZuAK7HWeMaOwzrQMGgAWThLG+QZe0sxlohYwfVPP+G65HBrWbgwSoE',
        src: "".concat(url, "adyen.js"),
        onLoad: handleLoad
      });
    })();
    return () => {
      const el = document.getElementById('addyenCSS');
      el.parentNode.removeChild(el);
      remove && remove();
    };
  }, [response]);
  (0, _react.useEffect)(() => {
    if (!response || !ready) return;
    (async () => {
      const _ref3 = window.AdyenWeb || {},
        AdyenCheckout = _ref3.AdyenCheckout,
        Dropin = _ref3.Dropin;
      const _response$configurati = response.configuration,
        _response$configurati2 = _response$configurati === void 0 ? {} : _response$configurati,
        amount = _response$configurati2.amount,
        holderName = _response$configurati2.cardHolderName,
        clientKey = _response$configurati2.clientKey,
        countryCode = _response$configurati2.countryCode,
        _response$configurati3 = _response$configurati2.environment,
        environment = _response$configurati3 === void 0 ? 'test' : _response$configurati3,
        id = _response$configurati2.id,
        returnUrl = _response$configurati2.returnUrl,
        locale = _response$configurati2.shopperLocale,
        sessionData = _response$configurati2.sessionData;
      const checkout = await AdyenCheckout({
        amount,
        clientKey,
        countryCode,
        environment,
        locale,
        returnUrl,
        session: {
          id,
          sessionData
        },
        onPaymentCompleted: (result, component) => {
          // eslint-disable-next-line no-console
          console.info(result, component);
          document.location.href = "".concat(returnUrl, "?").concat(new URLSearchParams(result).toString());
        },
        onPaymentFailed: (result, component) => {
          setError(error);
          // eslint-disable-next-line no-console
          console.info(result, component);
        },
        onError: (error, component) => {
          setError(error);
          // eslint-disable-next-line no-console
          console.error(error.name, error.message, error.stack, component);
        }
      });
      new Dropin(checkout, {
        paymentMethodsConfiguration: {
          card: {
            data: {
              holderName
            },
            hasHolderName: true,
            holderNameRequired: true
          }
        }
      }).mount(refContainer.current);
    })();

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ready, response]);
  const handleLoad = async () => {
    setReady(true);
  };
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ui.View, {
    ref: refContainer,
    className: style.container
  }, /*#__PURE__*/_react.default.createElement(_ui.Progress, {
    indeterminate: true,
    visible: !ready
  }), error && /*#__PURE__*/_react.default.createElement(_ui.Notification, {
    error: true,
    large: true,
    wide: true
  }, translate(_FormAdyen2.L10N.NOTIFICATION_ERROR))));
};
exports.FormAdyen = FormAdyen;
FormAdyen.displayName = 'Mirai:Payments:ButtonPayment:FormAdyen';
FormAdyen.propTypes = {
  cards: _propTypes.default.array,
  response: _propTypes.default.object
};
//# sourceMappingURL=FormAdyen.js.map