"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _navigators = require("../../../types/navigators");
var _display = require("../display");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
var _CommonRemoveModal = _interopRequireDefault(require("../../../components/modals/CommonRemoveModal"));
var _remove = require("../../../types/remove");
var _reactNative = require("react-native");
var _theme = require("../../../theme");
var _reactI18next = require("react-i18next");
var _Button = _interopRequireWildcard(require("../../../components/buttons/Button"));
var _testable = require("../../../utils/testable");
var _theme2 = require("../../../contexts/theme");
var _error = require("../../../types/error");
var _constants = require("../../../constants");
var _reactHooks = require("@credo-ts/react-hooks");
var _CredentialOfferAccept = _interopRequireDefault(require("../../../screens/CredentialOfferAccept"));
var _OpenIDCredentialRecordProvider = require("../context/OpenIDCredentialRecordProvider");
var _containerApi = require("../../../container-api");
var _Record = _interopRequireDefault(require("../../../components/record/Record"));
var _misc = require("../../../components/misc");
var _oca = require("../../../utils/oca");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
const OpenIDCredentialOffer = ({
  navigation,
  route
}) => {
  // FIXME: change params to accept credential id to avoid 'non-serializable' warnings
  const {
    credential
  } = route.params;
  const credentialDisplay = (0, _display.getCredentialForDisplay)(credential);
  const {
    display
  } = credentialDisplay;
  const {
    t,
    i18n
  } = (0, _reactI18next.useTranslation)();
  const {
    ColorPallet
  } = (0, _theme2.useTheme)();
  const {
    agent
  } = (0, _reactHooks.useAgent)();
  const {
    storeCredential
  } = (0, _OpenIDCredentialRecordProvider.useOpenIDCredentials)();
  const [isRemoveModalDisplayed, setIsRemoveModalDisplayed] = (0, _react.useState)(false);
  const [buttonsVisible, setButtonsVisible] = (0, _react.useState)(true);
  const [acceptModalVisible, setAcceptModalVisible] = (0, _react.useState)(false);
  const [bundleResolver] = (0, _containerApi.useServices)([_containerApi.TOKENS.UTIL_OCA_RESOLVER]);
  const [overlay, setOverlay] = (0, _react.useState)({
    bundle: undefined,
    presentationFields: [],
    metaOverlay: undefined,
    brandingOverlay: undefined
  });
  (0, _react.useEffect)(() => {
    if (!credentialDisplay || !bundleResolver || !i18n || !credentialDisplay.display) {
      return;
    }
    const resolveOverlay = async () => {
      const params = {
        identifiers: {
          schemaId: '',
          credentialDefinitionId: credentialDisplay.id
        },
        meta: {
          alias: credentialDisplay.display.issuer.name,
          credConnectionId: undefined,
          credName: credentialDisplay.display.name
        },
        attributes: (0, _oca.buildFieldsFromW3cCredsCredential)(credentialDisplay),
        language: i18n.language
      };
      const bundle = await bundleResolver.resolveAllBundles(params);
      setOverlay({
        ...bundle,
        presentationFields: bundle.presentationFields
      });
    };
    resolveOverlay();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [bundleResolver, i18n.language]);
  const styles = _reactNative.StyleSheet.create({
    headerTextContainer: {
      paddingHorizontal: 25,
      paddingVertical: 16
    },
    headerText: {
      ..._theme.TextTheme.normal,
      flexShrink: 1
    },
    footerButton: {
      paddingTop: 10
    }
  });
  const toggleDeclineModalVisible = () => setIsRemoveModalDisplayed(!isRemoveModalDisplayed);
  const handleDeclineTouched = async () => {
    var _navigation$getParent;
    toggleDeclineModalVisible();
    (_navigation$getParent = navigation.getParent()) === null || _navigation$getParent === void 0 || _navigation$getParent.navigate(_navigators.TabStacks.HomeStack, {
      screen: _navigators.Screens.Home
    });
  };
  const handleAcceptTouched = async () => {
    if (!agent) {
      return;
    }
    try {
      await storeCredential(credential);
      setAcceptModalVisible(true);
    } catch (err) {
      setButtonsVisible(true);
      const error = new _error.BifoldError(t('Error.Title1024'), t('Error.Message1024'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1024);
      _reactNative.DeviceEventEmitter.emit(_constants.EventTypes.ERROR_ADDED, error);
    }
  };
  const footerButton = (title, buttonPress, buttonType, testID, accessibilityLabel) => {
    return /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: styles.footerButton
    }, /*#__PURE__*/_react.default.createElement(_Button.default, {
      title: title,
      accessibilityLabel: accessibilityLabel,
      testID: testID,
      buttonType: buttonType,
      onPress: buttonPress,
      disabled: !buttonsVisible
    }));
  };
  const header = () => {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: styles.headerTextContainer
    }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
      style: styles.headerText,
      testID: (0, _testable.testIdWithKey)('HeaderText')
    }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, null, display.issuer.name || t('ContactDetails.AContact')), ' ', t('CredentialOffer.IsOfferingYouACredential'))), credential && /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: {
        marginHorizontal: 15,
        marginBottom: 16
      }
    }, /*#__PURE__*/_react.default.createElement(_misc.CredentialCard, {
      credential: credential
    })));
  };
  const footer = () => {
    const paddingHorizontal = 24;
    const paddingVertical = 16;
    const paddingBottom = 26;
    return /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: {
        marginBottom: 50
      }
    }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: {
        paddingHorizontal: paddingHorizontal,
        paddingVertical: paddingVertical,
        paddingBottom: paddingBottom,
        backgroundColor: ColorPallet.brand.secondaryBackground
      }
    }, footerButton(t('Global.Accept'), handleAcceptTouched, _Button.ButtonType.Primary, (0, _testable.testIdWithKey)('AcceptCredentialOffer'), t('Global.Accept')), footerButton(t('Global.Decline'), toggleDeclineModalVisible, _Button.ButtonType.Secondary, (0, _testable.testIdWithKey)('DeclineCredentialOffer'), t('Global.Decline'))));
  };
  const screenEdges = ['bottom', 'left', 'right'];
  return /*#__PURE__*/_react.default.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
    style: {
      flexGrow: 1
    },
    edges: screenEdges
  }, /*#__PURE__*/_react.default.createElement(_Record.default, {
    fields: overlay.presentationFields || [],
    hideFieldValues: true,
    header: header,
    footer: footer
  }), /*#__PURE__*/_react.default.createElement(_CredentialOfferAccept.default, {
    visible: acceptModalVisible,
    credentialId: '',
    confirmationOnly: true
  }), /*#__PURE__*/_react.default.createElement(_CommonRemoveModal.default, {
    usage: _remove.ModalUsage.CredentialOfferDecline,
    visible: isRemoveModalDisplayed,
    onSubmit: handleDeclineTouched,
    onCancel: toggleDeclineModalVisible
  }));
};
var _default = exports.default = OpenIDCredentialOffer;
//# sourceMappingURL=OpenIDCredentialOffer.js.map