"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AmazonPay = 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 _AmazonPay = require("./AmazonPay.constants");
var _AmazonPay2 = require("./AmazonPay.l10n");
var style = _interopRequireWildcard(require("./AmazonPay.module.css"));
var _helpers = require("./helpers");
var _ButtonPayment = require("../../../ButtonPayment/ButtonPayment.constants");
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 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); }
const error = new URLSearchParams(document.location.search).get('amazonPayErrorCode');
const storage = new _dataSources.Storage({
  adapter: _dataSources.LocalAdapter
});
const AmazonPay = _ref => {
  let {
    clientId = process.env.METHOD_AMAZON_CLIENT_ID,
    region,
    sellerId = process.env.METHOD_AMAZON_SELLER_ID,
    onError = () => {}
  } = _ref;
  const {
    locale,
    translate
  } = (0, _locale.useLocale)();
  const {
    value: {
      payment = {}
    } = {},
    set
  } = (0, _dataSources.useStore)();
  const [flow, setFlow] = (0, _react.useState)();
  const [orderReference, setOrderReference] = (0, _react.useState)(error ? storage.get(_AmazonPay.ORDER_REFERENCE_KEY) : undefined);
  const [ready, setReady] = (0, _react.useState)();
  (0, _react.useEffect)(() => {
    window.onAmazonLoginReady = handleLoginReady;
    window.onAmazonPaymentsReady = handlePaymentsReady;
    const exists = document.getElementById(_AmazonPay.SCRIPT_ID);
    if (!exists) {
      const script = document.createElement('script');
      script.id = _AmazonPay.SCRIPT_ID;
      script.async = 'async';
      script.src = (0, _helpers.getScriptUrl)({
        clientId,
        region,
        sellerId
      });
      document.head.appendChild(script);
      setReady(true);
    }
    return () => {
      const el = document.getElementById(_AmazonPay.SCRIPT_ID);
      el.parentNode.removeChild(el);
      window.onAmazonLoginReady = undefined;
      window.onAmazonPaymentsReady = undefined;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  (0, _react.useEffect)(() => {
    if (!ready) return;
    document.addEventListener(_ButtonPayment.EVENT.CTA_PRESS, handleButtonPress);
    document.addEventListener(_ButtonPayment.EVENT.AMAZON_PAY_RESPONSE, handleResponse);
    if (!orderReference) onError({
      error: true
    });
    return () => {
      document.removeEventListener(_ButtonPayment.EVENT.CTA_PRESS, handleButtonPress);
      document.removeEventListener(_ButtonPayment.EVENT.AMAZON_PAY_RESPONSE, handleResponse);
    };

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [flow, orderReference, ready]);
  (0, _react.useEffect)(() => {
    if (!error) return;
    onError({
      authorizeError: true
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [error]);
  const handleButtonPress = () => {
    // eslint-disable-next-line no-undef
    OffAmazonPayments.initConfirmationFlow(sellerId, orderReference, confirmationFlow => {
      setFlow(confirmationFlow);
      set({
        payment: _objectSpread(_objectSpread({}, payment), {}, {
          orderReference
        })
      });
    });
  };

  // eslint-disable-next-line no-undef
  const handleLoginReady = () => amazon.Login.setClientId(clientId);
  const handleOnComplete = () => {
    // eslint-disable-next-line no-undef
    new OffAmazonPayments.Widgets.Wallet(_objectSpread(_objectSpread({
      amazonOrderReferenceId: orderReference,
      sellerId
    }, _AmazonPay.OPTIONS_WALLET), {}, {
      onError: () => {
        var _document$querySelect, _document$querySelect2;
        // eslint-disable-next-line no-undef
        amazon.Login.logout();
        (_document$querySelect = document.querySelector("#".concat(_AmazonPay.WALLET_ID))) === null || _document$querySelect === void 0 ? void 0 : (_document$querySelect2 = _document$querySelect.firstChild) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.remove();
      },
      onOrderReferenceCreate: orderReferenceProp => {
        const orderReference = orderReferenceProp.getAmazonOrderReferenceId();
        setOrderReference(orderReference);
        storage.set(_AmazonPay.ORDER_REFERENCE_KEY, orderReference);
        onError({});
      },
      onPaymentSelect: () => onError({})
    })).bind(_AmazonPay.WALLET_ID);
  };
  const handlePaymentsReady = () => {
    var _LANGUAGES$locale;
    // eslint-disable-next-line no-undef
    OffAmazonPayments.Button(_AmazonPay.BUTTON_ID, sellerId, _objectSpread(_objectSpread({
      language: (_LANGUAGES$locale = _AmazonPay.LANGUAGES[locale]) !== null && _LANGUAGES$locale !== void 0 ? _LANGUAGES$locale : _AmazonPay.DEFAULT_LANGUAGE
    }, _AmazonPay.OPTIONS_BUTTON), {}, {
      authorization: () => {
        // eslint-disable-next-line no-undef
        amazon.Login.authorize(_AmazonPay.OPTIONS_AUTHORIZE).onComplete(handleOnComplete);
      }
    }));
    if (orderReference) handleOnComplete();
  };
  const handleResponse = _ref2 => {
    let {
      detail: {
        response
      } = {}
    } = _ref2;
    return response ? flow.success() : flow.error();
  };
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", {
    id: _AmazonPay.BUTTON_ID,
    className: style.button
  }), /*#__PURE__*/_react.default.createElement("div", {
    id: _AmazonPay.WALLET_ID,
    className: style.wallet
  }), error && /*#__PURE__*/_react.default.createElement(_ui.Notification, {
    error: true,
    small: true,
    wide: true,
    className: style.error
  }, translate(_AmazonPay.ERRORS[error] || _AmazonPay2.L10N.NOTIFICATION_AMAZON_UNKNOWN_ERROR)));
};
exports.AmazonPay = AmazonPay;
AmazonPay.displayName = 'Mirai:Payments:AmazonPay';
AmazonPay.propTypes = {
  clientId: _propTypes.default.string,
  region: _propTypes.default.string,
  sellerId: _propTypes.default.string,
  onError: _propTypes.default.func
};
//# sourceMappingURL=AmazonPay.js.map