"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FormPaycomet = void 0;
var _locale = require("@mirai/locale");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _FormPaycomet = require("./FormPaycomet.constants");
var _FormPaycomet2 = require("./FormPaycomet.l10n");
var style = _interopRequireWildcard(require("./FormPaycomet.module.css"));
var _helpers = require("./helpers");
var _InputField = require("../InputField");
const _excluded = ["currencyDecimals", "info", "publicKey", "onSuccess"];
/* eslint-disable react/no-unknown-property */
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 FormPaycomet = _ref => {
  let {
      currencyDecimals = 2,
      info: {
        amount
      } = {},
      publicKey = process.env.PROVIDER_PAYCOMET_PUBLICKEY,
      onSuccess = () => {}
    } = _ref,
    others = _objectWithoutProperties(_ref, _excluded);
  const {
    locale,
    translate
  } = (0, _locale.useLocale)();
  const formRef = (0, _react.useRef)();
  const tokenRef = (0, _react.useRef)();
  const errorRef = (0, _react.useRef)();
  (0, _helpers.useMutationObserver)(tokenRef.current, () => {
    const {
      value: nextToken = ''
    } = document.getElementById('paytpvToken') || {};
    if (nextToken.length > 0) setToken(nextToken);
  }, {
    attributes: true
  });
  (0, _helpers.useMutationObserver)(errorRef.current, () => {
    const {
      textContent: nextError = ''
    } = document.getElementById('paymentErrorMsg') || {};
    if ((nextError === null || nextError === void 0 ? void 0 : nextError.length) > 0) {
      setError(nextError);
      setBusy(false);
    }
  });
  const [busy, setBusy] = (0, _react.useState)(false);
  const [token, setToken] = (0, _react.useState)();
  const [error, setError] = (0, _react.useState)();
  const [expire, setExpire] = (0, _react.useState)({});
  (0, _react.useEffect)(() => {
    const exists = document.getElementById(_FormPaycomet.SCRIPT_ID);
    if (!exists) {
      const script = document.createElement('script');
      script.id = _FormPaycomet.SCRIPT_ID;
      script.src = "".concat(process.env.PROVIDER_PAYCOMET_SCRIPT, "?lang=").concat(locale.split('-')[0]);
      document.head.appendChild(script);
    }
    return () => {
      const el = document.getElementById(_FormPaycomet.SCRIPT_ID);
      if (el) el.parentNode.removeChild(el);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  (0, _react.useEffect)(() => {
    if (!token) return;
    setBusy(false);
    setError();
    onSuccess({
      token
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token]);
  const handleExpireChange = event => {
    const {
      name,
      value = ''
    } = event.target || {};
    setExpire(_objectSpread(_objectSpread({}, expire), {}, {
      [name]: value.replace(/[^\d]/g, '')
    }));
  };
  const handleCardTokenized = event => {
    event.preventDefault();
    setBusy(true);
  };
  const handlePress = event => {
    event.stopPropagation();
    const {
      current: form
    } = formRef;
    form.action = 'javascript:void(0)';
    form.submit();
  };
  const getInlineStyle = () => {
    const {
      inputColor,
      inputFontSize,
      font
    } = _ui.Theme.get();
    return {
      card_number: "border:0px;background-image:none;color:".concat(inputColor, ";font-family:").concat(font, ";font-size:").concat(inputFontSize, "px;outline: 0;padding:0!important;"),
      cvv: "border:0px;color:".concat(inputColor, ";font-family:").concat(font, ";font-size:").concat(inputFontSize, "px;padding:0!important;")
    };
  };
  const {
    card_number,
    cvv
  } = getInlineStyle();
  return /*#__PURE__*/_react.default.createElement(_ui.View, _extends({}, others, {
    className: (0, _ui.styles)(style.container, others.className)
  }), /*#__PURE__*/_react.default.createElement(_ui.Text, {
    action: true
  }, translate(_FormPaycomet2.L10N.LABEL_SECURE_PAGE)), /*#__PURE__*/_react.default.createElement("form", {
    ref: formRef,
    id: "paycometPaymentForm",
    onSubmit: handleCardTokenized
  }, /*#__PURE__*/_react.default.createElement("input", {
    type: "hidden",
    name: "amount",
    value: (amount * Math.pow(10, currencyDecimals)).toFixed()
  }), /*#__PURE__*/_react.default.createElement("input", {
    type: "hidden",
    "data-paycomet": "jetID",
    value: publicKey
  }), /*#__PURE__*/_react.default.createElement("input", {
    ref: tokenRef,
    type: "hidden",
    id: "paytpvToken",
    name: "paytpvToken",
    value: ""
  }), /*#__PURE__*/_react.default.createElement(_InputField.InputField, {
    label: translate(_FormPaycomet2.L10N.LABEL_CARD_NAME),
    value: "value"
  }, /*#__PURE__*/_react.default.createElement("input", {
    className: style.inputName,
    "aria-label": translate(_FormPaycomet2.L10N.LABEL_CARD_NAME),
    "data-paycomet": "cardHolderName"
  })), /*#__PURE__*/_react.default.createElement(_InputField.InputField, {
    label: translate(_FormPaycomet2.L10N.LABEL_CARD_NUMBER),
    value: "value"
  }, /*#__PURE__*/_react.default.createElement("div", {
    id: "paycomet-pan",
    className: style.inputName
  }), /*#__PURE__*/_react.default.createElement("input", {
    "aria-label": translate(_FormPaycomet2.L10N.LABEL_CARD_NUMBER),
    "paycomet-style": card_number,
    "paycomet-name": "pan",
    "paycomet-placeholder": translate(_FormPaycomet2.L10N.LABEL_CARD_NUMBER_PLACEHOLDER)
  })), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true
  }, /*#__PURE__*/_react.default.createElement(_InputField.InputField, {
    label: translate(_FormPaycomet2.L10N.LABEL_EXPIRATION),
    value: "value"
  }, /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true,
    className: style.inputName
  }, /*#__PURE__*/_react.default.createElement("input", {
    onChange: handleExpireChange,
    value: expire.month,
    name: "month",
    "data-paycomet": "dateMonth",
    maxLength: 2,
    className: style.inputExpire,
    "aria-label": translate(_FormPaycomet2.L10N.LABEL_EXPIRATION)
  }), "/", /*#__PURE__*/_react.default.createElement("input", {
    onChange: handleExpireChange,
    value: expire.year,
    name: "year",
    "data-paycomet": "dateYear",
    maxLength: 2,
    className: style.inputExpire,
    "aria-label": translate(_FormPaycomet2.L10N.LABEL_EXPIRATION)
  }))), /*#__PURE__*/_react.default.createElement(_InputField.InputField, {
    label: translate(_FormPaycomet2.L10N.LABEL_CVV),
    className: style.inputCVV,
    value: "value"
  }, /*#__PURE__*/_react.default.createElement("div", {
    id: "paycomet-cvc2",
    "data-paycomet": "cvc2",
    className: style.inputName
  }), /*#__PURE__*/_react.default.createElement("input", {
    "aria-label": translate(_FormPaycomet2.L10N.LABEL_CVV),
    "paycomet-name": "cvc2",
    "paycomet-style": cvv
  }))), /*#__PURE__*/_react.default.createElement(_ui.Button, {
    busy: busy,
    large: true,
    nativeTag: true,
    preventDefault: false,
    wide: true,
    onPress: handlePress,
    className: style.button
  }, translate(_FormPaycomet2.L10N.ACTION_PAY))), error && /*#__PURE__*/_react.default.createElement(_ui.Notification, {
    error: true,
    wide: true
  }, error), /*#__PURE__*/_react.default.createElement("div", {
    ref: errorRef,
    id: "paymentErrorMsg",
    style: {
      display: 'none'
    }
  }));
};
exports.FormPaycomet = FormPaycomet;
FormPaycomet.displayName = 'Mirai:Payments:ButtonPayment:FormPaycomet';
FormPaycomet.propTypes = {
  currencyDecimals: _propTypes.default.number,
  info: _propTypes.default.shape({
    amount: _propTypes.default.number
  }),
  publicKey: _propTypes.default.string.isRequired,
  onSuccess: _propTypes.default.func
};
//# sourceMappingURL=FormPaycomet.js.map