"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 _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; }
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 _ref$cards = _ref.cards,
    cards = _ref$cards === void 0 ? [] : _ref$cards,
    publicKey = _ref.publicKey,
    requiredText = _ref.requiredText,
    _ref$showCVV = _ref.showCVV,
    showCVV = _ref$showCVV === void 0 ? true : _ref$showCVV,
    _ref$showErrors = _ref.showErrors,
    showErrors = _ref$showErrors === void 0 ? false : _ref$showErrors,
    _ref$onChange = _ref.onChange,
    onChange = _ref$onChange === void 0 ? () => {} : _ref$onChange,
    _ref$onError = _ref.onError,
    onError = _ref$onError === void 0 ? () => {} : _ref$onError,
    others = _objectWithoutProperties(_ref, _excluded);
  const _useDevice = (0, _ui.useDevice)(),
    isMobile = _useDevice.isMobile;
  const _useLocale = (0, _locale.useLocale)(),
    translate = _useLocale.translate;
  const _useStore = (0, _dataSources.useStore)(),
    _useStore$value = _useStore.value,
    _useStore$value2 = _useStore$value === void 0 ? {} : _useStore$value,
    _useStore$value2$paym = _useStore$value2.payment,
    payment = _useStore$value2$paym === void 0 ? {} : _useStore$value2$paym,
    value = _useStore.value,
    set = _useStore.set;
  const _useState = (0, _react.useState)(),
    _useState2 = _slicedToArray(_useState, 2),
    focus = _useState2[0],
    setFocus = _useState2[1];
  const _useState3 = (0, _react.useState)({}),
    _useState4 = _slicedToArray(_useState3, 2),
    form = _useState4[0],
    setForm = _useState4[1];
  const _useState5 = (0, _react.useState)(_objectSpread({
      card: {},
      name: {},
      expire: {}
    }, showCVV ? {
      cvv: {}
    } : undefined)),
    _useState6 = _slicedToArray(_useState5, 2),
    formError = _useState6[0],
    setFormError = _useState6[1];
  const _useState7 = (0, _react.useState)(false),
    _useState8 = _slicedToArray(_useState7, 2),
    ready = _useState8[0],
    setReady = _useState8[1];
  const _useState9 = (0, _react.useState)(false),
    _useState0 = _slicedToArray(_useState9, 2),
    responseError = _useState0[0],
    setResponseError = _useState0[1];
  (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 || _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 _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [],
          _ref3 = _slicedToArray(_ref2, 2),
          value = _ref3[1];
        return cards.includes(value);
      }).map(function () {
        let _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [],
          _ref5 = _slicedToArray(_ref4, 1),
          key = _ref5[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 || _secureFields2.on('change', handleChangeSecure);
    (_secureFields3 = secureFields) === null || _secureFields3 === void 0 || _secureFields3.on('error', handleTokenError);
    (_secureFields4 = secureFields) === null || _secureFields4 === void 0 || _secureFields4.on('ready', handleReady);
    (_secureFields5 = secureFields) === null || _secureFields5 === 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(_ref6 => {
      let _ref7 = _slicedToArray(_ref6, 2),
        value = _ref7[1];
      return value !== undefined;
    })));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formError, responseError]);
  const handleButtonPress = () => {
    if (Object.entries(formError).filter(_ref8 => {
      let _ref9 = _slicedToArray(_ref8, 2),
        value = _ref9[1];
      return value !== undefined;
    }).length > 0) return;
    setResponseError();
    const _form$expire$split = form.expire.split('/'),
      _form$expire$split2 = _slicedToArray(_form$expire$split, 2),
      month = _form$expire$split2[0],
      year = _form$expire$split2[1];
    secureFields.submit({
      expm: month,
      expy: year
    });
  };
  const handleChange = function (field) {
    let value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    setResponseError();
    const _formatValues = (0, _helpers.formatValues)(_objectSpread(_objectSpread({}, {
        expire: form.expire,
        name: form.name
      }), {}, {
        [field]: value
      }), form),
      expire = _formatValues.expire,
      name = _formatValues.name;
    setForm(_objectSpread(_objectSpread({}, form), {}, {
      expire,
      name
    }));
  };
  const handleChangeSecure = _ref0 => {
    let _ref0$fields = _ref0.fields,
      _ref0$fields2 = _ref0$fields === void 0 ? {} : _ref0$fields,
      _ref0$fields2$cardNum = _ref0$fields2.cardNumber,
      cardNumber = _ref0$fields2$cardNum === void 0 ? {} : _ref0$fields2$cardNum,
      _ref0$fields2$cvv = _ref0$fields2.cvv,
      cvv = _ref0$fields2$cvv === void 0 ? {} : _ref0$fields2$cvv,
      _ref0$event = _ref0.event,
      _ref0$event2 = _ref0$event === void 0 ? {} : _ref0$event,
      type = _ref0$event2.type,
      field = _ref0$event2.field;
    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 _ref1 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      required = _ref1.required,
      test = _ref1.test;
    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 = _ref10 => {
    let transactionId = _ref10.transactionId;
    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.testId;
  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