"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FormCheckout = void 0;
var _locale = require("@mirai/locale");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _FormCheckout = require("./FormCheckout.constants");
var _FormCheckout2 = require("./FormCheckout.l10n");
var style = _interopRequireWildcard(require("./FormCheckout.module.css"));
var _helpers = require("./helpers");
var _loadScript = require("../../../../../helpers/loadScript");
var _InputField = require("../InputField");
const _excluded = ["publicKey", "onError", "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 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 FormCheckout = _ref => {
  let {
      publicKey = process.env.PROVIDER_CHECKOUT_PUBLICKEY,
      onError = () => {},
      onSuccess = () => {}
    } = _ref,
    others = _objectWithoutProperties(_ref, _excluded);
  const {
    translate
  } = (0, _locale.useLocale)();
  const [busy, setBusy] = (0, _react.useState)(false);
  const [focus, setFocus] = (0, _react.useState)();
  const [form, setForm] = (0, _react.useState)({});
  const [formError, setFormError] = (0, _react.useState)({});
  const [ready, setReady] = (0, _react.useState)(false);
  const [responseError, setResponseError] = (0, _react.useState)();
  (0, _react.useEffect)(() => {
    (0, _loadScript.loadScript)({
      domain: 'payment',
      id: 'checkout',
      src: "".concat(process.env.SERVICE_STATIC, "/payments/scripts/framesv2.min.js"),
      onLoad: handleLoad
    });
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  []);
  (0, _react.useEffect)(() => {
    if (!ready) return;
    const {
      Frames
    } = window || {};
    const handleBlur = _ref2 => {
      let {
        element
      } = _ref2;
      return handleLeave(element);
    };
    const handleFocus = _ref3 => {
      let {
        element
      } = _ref3;
      return handleEnter(element);
    };
    const handleValidationChanged = _ref4 => {
      let {
        element,
        isEmpty,
        isValid
      } = _ref4;
      handleChange(element, isEmpty ? undefined : 'value');
      handleError(element, !isValid);
    };
    Frames.addEventHandler(Frames.Events.FRAME_BLUR, handleBlur);
    Frames.addEventHandler(Frames.Events.FRAME_FOCUS, handleFocus);
    Frames.addEventHandler(Frames.Events.CARD_TOKENIZED, handleCardTokenized);
    Frames.addEventHandler(Frames.Events.CARD_TOKENIZATION_FAILED, handleCardTokenizedFailed);
    Frames.addEventHandler(Frames.Events.FRAME_VALIDATION_CHANGED, handleValidationChanged);
    return () => {
      Frames.removeEventHandler(Frames.Events.FRAME_BLUR, handleBlur);
      Frames.removeEventHandler(Frames.Events.FRAME_FOCUS, handleFocus);
      Frames.removeEventHandler(Frames.Events.CARD_TOKENIZED, handleCardTokenized);
      Frames.removeEventHandler(Frames.Events.CARD_TOKENIZATION_FAILED, handleCardTokenizedFailed);
      Frames.removeEventHandler(Frames.Events.FRAME_VALIDATION_CHANGED, handleValidationChanged);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [form, formError, ready]);
  const handleCardTokenized = function () {
    var _window$Frames;
    let {
      token
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    setBusy(false);
    if (!token) return;
    setForm({});
    setFormError({});
    (_window$Frames = window.Frames) === null || _window$Frames === void 0 ? void 0 : _window$Frames.init(_objectSpread({
      publicKey
    }, (0, _helpers.getStyle)()));
    onSuccess({
      name: form === null || form === void 0 ? void 0 : form.name,
      token
    });
  };
  const handleCardTokenizedFailed = function () {
    var _window$Frames2;
    let error = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    setBusy(false);
    setResponseError(error);
    (_window$Frames2 = window.Frames) === null || _window$Frames2 === void 0 ? void 0 : _window$Frames2.enableSubmitForm();
    onError(error);
  };
  const handleChange = function (field) {
    let value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    setForm(_objectSpread(_objectSpread({}, form), {}, {
      [field]: value
    }));
    setFormError(_objectSpread(_objectSpread({}, formError), {}, {
      [field]: value.length === 0
    }));
  };
  const handleError = (field, value) => {
    setFormError(_objectSpread(_objectSpread({}, formError), {}, {
      [field]: value
    }));
  };
  const handleEnter = field => setFocus(focus => _objectSpread(_objectSpread({}, focus), {}, {
    [field]: true
  }));
  const handleLeave = field => setFocus(focus => _objectSpread(_objectSpread({}, focus), {}, {
    [field]: false
  }));
  const handleLoad = () => {
    var _window$Frames3;
    (_window$Frames3 = window.Frames) === null || _window$Frames3 === void 0 ? void 0 : _window$Frames3.init(_objectSpread({
      publicKey
    }, (0, _helpers.getStyle)()));
    setReady(true);
  };
  const handlePress = () => {
    const {
      Frames
    } = window || {};
    setBusy(true);
    setResponseError();
    Frames.cardholder = {
      name: form.name
    };
    Frames.submitCard();
  };
  const hasError = Object.values(formError).length < _FormCheckout.FIELDS_COUNT || Object.values(formError).some(value => value === true);
  return /*#__PURE__*/_react.default.createElement(_ui.View, others, /*#__PURE__*/_react.default.createElement(_ui.Text, {
    action: true,
    className: style.description
  }, translate(_FormCheckout2.L10N.LABEL_SECURE_PAGE)), /*#__PURE__*/_react.default.createElement(_InputField.InputField, {
    label: translate(_FormCheckout2.L10N.LABEL_CARD_NAME),
    error: formError.name,
    focus: focus === null || focus === void 0 ? void 0 : focus.name,
    success: formError.name === false,
    value: form.name
  }, /*#__PURE__*/_react.default.createElement(_ui.Input, {
    name: "name",
    value: form.name,
    onChange: value => handleChange('name', value),
    onEnter: () => handleEnter('name'),
    onLeave: () => handleLeave('name'),
    className: style.name,
    "aria-label": translate(_FormCheckout2.L10N.LABEL_CARD_NAME)
  })), /*#__PURE__*/_react.default.createElement(_InputField.InputField, {
    label: translate(_FormCheckout2.L10N.LABEL_CARD_NUMBER),
    error: formError['card-number'],
    focus: focus === null || focus === void 0 ? void 0 : focus['card-number'],
    success: formError['card-number'] === false,
    value: form === null || form === void 0 ? void 0 : form['card-number']
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _ui.styles)(style.frame, 'card-number-frame')
  })), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true
  }, /*#__PURE__*/_react.default.createElement(_InputField.InputField, {
    label: translate(_FormCheckout2.L10N.LABEL_EXPIRATION),
    error: formError['expiry-date'],
    focus: focus === null || focus === void 0 ? void 0 : focus['expiry-date'],
    success: formError['expiry-date'] === false,
    value: form === null || form === void 0 ? void 0 : form['expiry-date']
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _ui.styles)(style.frame, 'expiry-date-frame')
  })), /*#__PURE__*/_react.default.createElement(_InputField.InputField, {
    label: translate(_FormCheckout2.L10N.LABEL_CVV),
    error: formError['cvv'],
    focus: focus === null || focus === void 0 ? void 0 : focus['cvv'],
    success: formError['cvv'] === false,
    value: form === null || form === void 0 ? void 0 : form['cvv'],
    className: style.inputCVV
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _ui.styles)(style.frame, 'cvv-frame')
  }))), responseError && /*#__PURE__*/_react.default.createElement(_ui.Notification, {
    error: true,
    small: true,
    wide: true
  }, translate(_FormCheckout2.L10N.NOTIFICATION_ERROR_CHECKOUT)), /*#__PURE__*/_react.default.createElement(_ui.Button, {
    busy: busy,
    disabled: hasError,
    large: true,
    wide: true,
    onPress: handlePress,
    className: style.button
  }, translate(_FormCheckout2.L10N.ACTION_PAY)));
};
exports.FormCheckout = FormCheckout;
FormCheckout.displayName = 'Mirai:Payments:ButtonPayment:FormCheckout';
FormCheckout.propTypes = {
  publicKey: _propTypes.default.string.isRequired,
  onError: _propTypes.default.func,
  onSuccess: _propTypes.default.func
};
//# sourceMappingURL=FormCheckout.js.map