"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PCI = 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 _helpers = require("./helpers");
var _PCI = require("./PCI.constants");
var _PCI2 = require("./PCI.l10n");
var style = _interopRequireWildcard(require("./PCI.module.css"));
var _trackError = require("../../../../../helpers/trackError");
var _ButtonPayment = require("../../../ButtonPayment/ButtonPayment.constants");
var _InputField = require("../../../ButtonPayment/components/InputField");
var _testExpire = require("../Card/helpers/testExpire");
const _excluded = ["cards", "publicKey", "requiredText", "showCVV", "showErrors", "onChange", "onError"];
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; }
let secureFields;
const PCI = _ref => {
  var _form$card, _form$name, _form$name2, _form$expire, _form$expire2, _form$cvv;
  let {
      cards = [],
      publicKey,
      requiredText,
      showCVV = true,
      showErrors = false,
      onChange = () => {},
      onError = () => {}
    } = _ref,
    others = _objectWithoutProperties(_ref, _excluded);
  const {
    isMobile
  } = (0, _ui.useDevice)();
  const {
    translate
  } = (0, _locale.useLocale)();
  const {
    value: {
      payment = {}
    } = {},
    value,
    set
  } = (0, _dataSources.useStore)();
  const [focus, setFocus] = (0, _react.useState)();
  const [form, setForm] = (0, _react.useState)({});
  const [formError, setFormError] = (0, _react.useState)(_objectSpread({
    card: {},
    name: {},
    expire: {}
  }, showCVV ? {
    cvv: {}
  } : undefined));
  const [ready, setReady] = (0, _react.useState)(false);
  const [responseError, setResponseError] = (0, _react.useState)(false);
  (0, _react.useEffect)(() => {
    const exists = document.getElementById(_PCI.SCRIPT_ID);
    if (!exists) {
      const script = document.createElement('script');
      script.id = _PCI.SCRIPT_ID;
      script.src = process.env.METHOD_PCIPROXY_SCRIPT;
      script.onload = handleLoad;
      document.head.appendChild(script);
    }
    return () => {
      var _secureFields;
      const el = document.getElementById(_PCI.SCRIPT_ID);
      el.parentNode.removeChild(el);
      (_secureFields = secureFields) === null || _secureFields === void 0 ? void 0 : _secureFields.destroy();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  (0, _react.useEffect)(() => {
    if (!ready || !publicKey) return;
    onError(formError);

    // eslint-disable-next-line no-undef
    secureFields = new SecureFields();
    secureFields.initTokenize(publicKey, _objectSpread({
      cardNumber: 'card'
    }, showCVV ? {
      cvv: 'cvv'
    } : undefined), _objectSpread(_objectSpread({}, (0, _helpers.getStyle)()), {}, {
      paymentMethods: Object.entries(_PCI.CARDS).filter(function () {
        let [, value] = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        return cards.includes(value);
      }).map(function () {
        let [key] = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        return key;
      })
    }));

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [publicKey, ready]);
  (0, _react.useEffect)(() => {
    var _secureFields2, _secureFields3, _secureFields4, _secureFields5;
    (_secureFields2 = secureFields) === null || _secureFields2 === void 0 ? void 0 : _secureFields2.on('change', handleChangeSecure);
    (_secureFields3 = secureFields) === null || _secureFields3 === void 0 ? void 0 : _secureFields3.on('error', handleTokenError);
    (_secureFields4 = secureFields) === null || _secureFields4 === void 0 ? void 0 : _secureFields4.on('ready', handleReady);
    (_secureFields5 = secureFields) === null || _secureFields5 === void 0 ? void 0 : _secureFields5.on('success', handleSuccess);
    document.addEventListener(_ButtonPayment.EVENT.CTA_PRESS, handleButtonPress);
    if (Object.keys(formError).length === 0) onError({});
    return () => document.removeEventListener(_ButtonPayment.EVENT.CTA_PRESS, handleButtonPress);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [focus, form, formError, ready, responseError, value]);
  (0, _react.useEffect)(() => {
    onChange({
      expire: form.expire,
      name: form.name,
      type: form.type
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [form]);
  (0, _react.useEffect)(() => {
    onError(Object.fromEntries(Object.entries(formError).filter(_ref2 => {
      let [, value] = _ref2;
      return value !== undefined;
    })));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formError, responseError]);
  const handleButtonPress = () => {
    if (Object.entries(formError).filter(_ref3 => {
      let [, value] = _ref3;
      return value !== undefined;
    }).length > 0) return;
    setResponseError();
    const [month, year] = form.expire.split('/');
    secureFields.submit({
      expm: month,
      expy: year
    });
  };
  const handleChange = function (field) {
    let value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    setResponseError();
    const {
      expire,
      name
    } = (0, _helpers.formatValues)(_objectSpread(_objectSpread({}, {
      expire: form.expire,
      name: form.name
    }), {}, {
      [field]: value
    }), form);
    setForm(_objectSpread(_objectSpread({}, form), {}, {
      expire,
      name
    }));
  };
  const handleChangeSecure = _ref4 => {
    let {
      fields: {
        cardNumber = {},
        cvv = {}
      } = {},
      event: {
        type,
        field
      } = {}
    } = _ref4;
    const fieldName = field === 'cardNumber' ? 'card' : field;
    if (type === 'focus') return handleEnter(fieldName);
    const isEvent = ['blur', 'keyUp'].includes(type);
    const isCardEmpty = fieldName === 'card' && cardNumber.length === 0 && !form.card;
    const isCvvEmpty = fieldName === 'cvv' && cvv.length === 0 && !form.cvv;
    if (!isEvent || isEvent && (isCardEmpty || isCvvEmpty)) {
      return type === 'blur' ? handleLeave(fieldName) : undefined;
    }
    setResponseError();
    const error = _objectSpread({}, formError);
    if (fieldName === 'card') {
      setForm(_objectSpread(_objectSpread({}, form), {}, {
        card: cardNumber,
        type: cardNumber.valid ? _PCI.CARDS[cardNumber.paymentMethod] : undefined
      }));
      error.card = !cardNumber.valid && cardNumber.length > 0 ? {
        format: true
      } : cardNumber.length === 0 ? {
        required: true
      } : undefined;
    } else if (fieldName === 'cvv') {
      setForm(_objectSpread(_objectSpread({}, form), {}, {
        cvv
      }));
      error.cvv = !cvv.valid && cvv.length > 0 ? {
        format: true
      } : cvv.length === 0 ? {
        required: true
      } : undefined;
    }
    if (type === 'blur') handleLeave(fieldName);
    setFormError(error);
  };
  const handleEnter = field => setFocus(focus => _objectSpread(_objectSpread({}, focus), {}, {
    [field]: true
  }));
  const handleLeave = field => setFocus(focus => _objectSpread(_objectSpread({}, focus), {}, {
    [field]: false
  }));
  const handleError = function (field) {
    let {
      required,
      test
    } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    if (!ready) return;
    setFormError(formError => _objectSpread(_objectSpread({}, formError), {
      [field]: required ? {
        required: true
      } : test ? {
        format: true
      } : undefined
    }));
  };
  const handleLoad = () => {
    setReady(true);
  };
  const handleReady = () => {
    secureFields.setPlaceholder('cardNumber', _PCI.PLACEHOLDER_CARD);
    showCVV && secureFields.setPlaceholder('cvv', _PCI.PLACEHOLDER_CVV);
  };
  const handleSuccess = _ref5 => {
    let {
      transactionId
    } = _ref5;
    set({
      payment: _objectSpread(_objectSpread({}, payment), {}, {
        transactionId
      })
    });
  };
  const handleTokenError = function () {
    let error = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    if (error) (0, _trackError.trackError)('PCI', error instanceof Error ? error.stack : error === null || error === void 0 ? void 0 : error.message);
    setResponseError(_PCI.ERROR);
    set({
      payment: _objectSpread(_objectSpread({}, payment), {}, {
        error: _PCI.ERROR
      })
    });
  };
  const {
    testId
  } = others;
  return /*#__PURE__*/_react.default.createElement(_ui.View, others, /*#__PURE__*/_react.default.createElement(_ui.Text, {
    action: true
  }, translate(_PCI2.L10N.LABEL_SECURE_PAGE)), /*#__PURE__*/_react.default.createElement(_InputField.InputField, {
    id: "checkout-card",
    error: showErrors && (!form.card || ((_form$card = form.card) === null || _form$card === void 0 ? void 0 : _form$card.length) === 0) || Object.keys(formError.card || {}).length > 0,
    focus: focus === null || focus === void 0 ? void 0 : focus.card,
    label: translate(_PCI2.L10N.LABEL_CARD_NUMBER),
    requiredText: requiredText,
    showRequired: true,
    success: !formError.card,
    value: form.card,
    testId: testId ? "".concat(testId, "-PCI-card") : undefined
  }, /*#__PURE__*/_react.default.createElement("div", {
    id: "card",
    className: style.input
  })), /*#__PURE__*/_react.default.createElement(_InputField.InputField, {
    error: showErrors && (!form.name || ((_form$name = form.name) === null || _form$name === void 0 ? void 0 : _form$name.length) === 0) || Object.keys(formError.name || {}).length > 0,
    focus: focus === null || focus === void 0 ? void 0 : focus.name,
    label: translate(_PCI2.L10N.LABEL_CARD_NAME),
    requiredText: requiredText,
    showRequired: true,
    success: ((_form$name2 = form.name) === null || _form$name2 === void 0 ? void 0 : _form$name2.length) > 0 && !formError.name,
    value: form.name,
    testId: testId ? "".concat(testId, "-PCI-name") : undefined
  }, /*#__PURE__*/_react.default.createElement(_ui.Input, {
    id: "checkout-name",
    name: "name",
    required: true,
    value: form.name,
    onChange: value => handleChange('name', value),
    onEnter: () => handleEnter('name'),
    onError: error => handleError('name', error),
    onLeave: () => handleLeave('name'),
    "aria-label": translate(_PCI2.L10N.LABEL_CARD_NAME)
  })), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: !isMobile,
    className: !isMobile && style.container
  }, /*#__PURE__*/_react.default.createElement(_InputField.InputField, {
    error: showErrors && (!form.expire || ((_form$expire = form.expire) === null || _form$expire === void 0 ? void 0 : _form$expire.length) === 0) || Object.keys(formError.expire || {}).length > 0,
    focus: focus === null || focus === void 0 ? void 0 : focus.expire,
    label: translate(_PCI2.L10N.LABEL_EXPIRATION),
    requiredText: requiredText,
    showRequired: true,
    success: ((_form$expire2 = form.expire) === null || _form$expire2 === void 0 ? void 0 : _form$expire2.length) > 0 && !formError.expire,
    value: form.expire,
    testId: testId ? "".concat(testId, "-PCI-expire") : undefined
  }, /*#__PURE__*/_react.default.createElement(_ui.Input, {
    id: "checkout-expire",
    maxLength: 5,
    name: "expire",
    placeholder: "".concat(translate(_PCI2.L10N.LABEL_MONTH_FORMAT), "/").concat(translate(_PCI2.L10N.LABEL_YEAR_FORMAT)),
    required: true,
    test: expire => expire.length === 0 || (expire === null || expire === void 0 ? void 0 : expire.length) > 0 && (0, _testExpire.testExpire)(expire),
    value: form.expire,
    onChange: value => handleChange('expire', value),
    onEnter: () => handleEnter('expire'),
    onError: error => handleError('expire', error),
    onLeave: () => handleLeave('expire'),
    "aria-label": translate(_PCI2.L10N.LABEL_EXPIRATION)
  })), showCVV && /*#__PURE__*/_react.default.createElement(_InputField.InputField, {
    id: "checkout-cvv",
    error: showErrors && (!form.cvv || ((_form$cvv = form.cvv) === null || _form$cvv === void 0 ? void 0 : _form$cvv.length) === 0) || Object.keys(formError.cvv || {}).length > 0,
    focus: focus === null || focus === void 0 ? void 0 : focus.cvv,
    label: translate(_PCI2.L10N.LABEL_CVV),
    requiredText: requiredText,
    showRequired: true,
    success: !formError.cvv,
    value: form.cvv,
    testId: testId ? "".concat(testId, "-PCI-CVV") : undefined
  }, /*#__PURE__*/_react.default.createElement("div", {
    id: "cvv",
    className: style.input
  }))), responseError && /*#__PURE__*/_react.default.createElement(_ui.Notification, {
    error: true,
    small: true,
    wide: true
  }, translate(_PCI2.L10N.NOTIFICATION_ERROR_PCI)));
};
exports.PCI = PCI;
PCI.displayName = 'Mirai:Payments:PCI';
PCI.propTypes = {
  cards: _propTypes.default.array,
  publicKey: _propTypes.default.string,
  requiredText: _propTypes.default.string,
  showCVV: _propTypes.default.bool,
  showErrors: _propTypes.default.bool,
  onChange: _propTypes.default.func,
  onError: _propTypes.default.func
};
//# sourceMappingURL=PCI.js.map