"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = require("react");
var _reactNative = require("react-native");
var _reactHooks = require("@credo-ts/react-hooks");
var _reactI18next = require("react-i18next");
var _navigators = require("../../../types/navigators");
var _displayProof = require("../displayProof");
var _testable = require("../../../utils/testable");
var _CommonRemoveModal = _interopRequireDefault(require("../../../components/modals/CommonRemoveModal"));
var _remove = require("../../../types/remove");
var _Button = _interopRequireWildcard(require("../../../components/buttons/Button"));
var _theme = require("../../../contexts/theme");
var _error = require("../../../types/error");
var _constants = require("../../../constants");
var _resolverProof = require("../resolverProof");
var _ProofRequestAccept = _interopRequireDefault(require("../../../screens/ProofRequestAccept"));
var _OpenIDCredentialRecordProvider = require("../context/OpenIDCredentialRecordProvider");
var _misc = require("../../../components/misc");
var _display = require("../display");
var _oca = require("../../../utils/oca");
var _ScreenLayout = _interopRequireDefault(require("../../../layout/ScreenLayout"));
var _utils = require("../utils/utils");
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; }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const OpenIDProofPresentation = ({
  navigation,
  route: {
    params: {
      credential
    }
  }
}) => {
  const [declineModalVisible, setDeclineModalVisible] = (0, _react.useState)(false);
  const [buttonsVisible, setButtonsVisible] = (0, _react.useState)(true);
  const [acceptModalVisible, setAcceptModalVisible] = (0, _react.useState)(false);
  const [credentialsRequested, setCredentialsRequested] = (0, _react.useState)([]);
  const {
    getW3CCredentialById,
    getSdJwtCredentialById
  } = (0, _OpenIDCredentialRecordProvider.useOpenIDCredentials)();
  const {
    ColorPallet,
    ListItems,
    TextTheme
  } = (0, _theme.useTheme)();
  const {
    t
  } = (0, _reactI18next.useTranslation)();
  const {
    agent
  } = (0, _reactHooks.useAgent)();
  const toggleDeclineModalVisible = () => setDeclineModalVisible(!declineModalVisible);
  const styles = _reactNative.StyleSheet.create({
    pageContent: {
      flexGrow: 1,
      justifyContent: 'space-between',
      padding: 10
    },
    credentialsList: {
      marginTop: 20,
      justifyContent: 'space-between'
    },
    headerTextContainer: {
      paddingVertical: 16
    },
    headerText: {
      ...ListItems.recordAttributeText,
      flexShrink: 1
    },
    footerButton: {
      paddingTop: 10
    },
    cardContainer: {
      paddingHorizontal: 25,
      paddingVertical: 16,
      backgroundColor: ColorPallet.brand.secondaryBackground,
      marginBottom: 20
    },
    cardAttributes: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      borderColor: ColorPallet.grayscale.lightGrey,
      borderWidth: 1,
      borderRadius: 8,
      padding: 8
    },
    cardGroupContainer: {
      borderRadius: 8,
      borderWidth: 2,
      borderColor: 'rgba(255, 255, 255, 0.2)'
    },
    cardGroupHeader: {
      padding: 8,
      marginVertical: 8
    }
  });
  const submission = (0, _react.useMemo)(() => credential && credential.credentialsForRequest ? (0, _displayProof.formatDifPexCredentialsForRequest)(credential.credentialsForRequest) : undefined, [credential]);
  const selectedCredentials = (0, _react.useMemo)(() => submission === null || submission === void 0 ? void 0 : submission.entries.reduce((acc, entry) => {
    if (entry.isSatisfied) {
      //TODO: Support multiplae credentials
      return {
        ...acc,
        [entry.inputDescriptorId]: {
          id: entry.credentials[0].id,
          claimFormat: entry.credentials[0].claimFormat
        }
      };
    }
    return acc;
  }, {}), [submission]);
  (0, _react.useEffect)(() => {
    async function fetchCreds() {
      if (!selectedCredentials) return;
      const creds = [];
      for (const [inputDescriptorID, {
        id,
        claimFormat
      }] of Object.entries(selectedCredentials)) {
        let credential;
        if ((0, _utils.isW3CProofRequest)(claimFormat)) {
          credential = await getW3CCredentialById(id);
        } else if ((0, _utils.isSdJwtProofRequest)(claimFormat)) {
          credential = await getSdJwtCredentialById(id);
        }
        if (credential && inputDescriptorID) {
          creds.push(credential);
        }
      }
      setCredentialsRequested(creds);
    }
    fetchCreds();
  }, [selectedCredentials, getW3CCredentialById, getSdJwtCredentialById]);
  const {
    verifierName
  } = (0, _react.useMemo)(() => {
    return {
      verifierName: credential === null || credential === void 0 ? void 0 : credential.verifierHostName
    };
  }, [credential]);
  const handleAcceptTouched = async () => {
    try {
      if (!agent || !credential.credentialsForRequest || !selectedCredentials) {
        return;
      }
      await (0, _resolverProof.shareProof)({
        agent,
        authorizationRequest: credential.authorizationRequest,
        credentialsForRequest: credential.credentialsForRequest,
        selectedCredentials
      });
      setAcceptModalVisible(true);
    } catch (err) {
      setButtonsVisible(true);
      const error = new _error.BifoldError(t('Error.Title1027'), t('Error.Message1027'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1027);
      _reactNative.DeviceEventEmitter.emit(_constants.EventTypes.ERROR_ADDED, error);
    }
  };
  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 handleDismiss = async () => {
    var _navigation$getParent2;
    (_navigation$getParent2 = navigation.getParent()) === null || _navigation$getParent2 === void 0 || _navigation$getParent2.navigate(_navigators.TabStacks.HomeStack, {
      screen: _navigators.Screens.Home
    });
  };
  const renderHeader = () => {
    return /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.headerTextContainer
    }, /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: styles.headerText,
      testID: (0, _testable.testIdWithKey)('HeaderText')
    }, /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: TextTheme.normal
    }, t('ProofRequest.ReceiveProofTitle')), '\n', /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: TextTheme.title
    }, verifierName ? verifierName : '')));
  };
  const selectAltCredentail = () => {};
  const renderCard = (sub, selectedCredential, hasMultipleCreds) => {
    const credential = credentialsRequested.find(c => c.id === selectedCredential.id);
    if (!credential) {
      return null;
    }
    const credentialDisplay = (0, _display.getCredentialForDisplay)(credential);
    const fields = (0, _oca.buildFieldsFromW3cCredsCredential)(credentialDisplay);
    const requestedAttributes = selectedCredential.requestedAttributes;
    const fieldsMapped = fields.filter(field => requestedAttributes === null || requestedAttributes === void 0 ? void 0 : requestedAttributes.includes(field.name));
    return /*#__PURE__*/React.createElement(_misc.CredentialCard, {
      credential: credential,
      displayItems: fieldsMapped,
      hasAltCredentials: hasMultipleCreds,
      handleAltCredChange: selectAltCredentail
    });
  };
  const renderBody = () => {
    if (!submission) return null;
    return /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.credentialsList
    }, submission.entries.map((s, i) => {
      //TODO: Support multiplae credentials
      const selectedCredential = s.credentials[0];
      const globalSubmissionName = submission.name;
      const globalSubmissionPurpose = submission.purpose;
      const submissionName = s.name;
      const submissionPurpose = s.purpose;
      const name = submissionName || globalSubmissionName || undefined;
      const purpose = submissionPurpose || globalSubmissionPurpose || undefined;
      return /*#__PURE__*/React.createElement(_reactNative.View, {
        key: i
      }, /*#__PURE__*/React.createElement(_reactNative.View, {
        style: styles.cardContainer
      }, /*#__PURE__*/React.createElement(_reactNative.View, {
        style: styles.cardGroupContainer
      }, name && purpose && /*#__PURE__*/React.createElement(_reactNative.View, {
        style: styles.cardGroupHeader
      }, /*#__PURE__*/React.createElement(_reactNative.Text, {
        style: TextTheme.labelSubtitle
      }, name), /*#__PURE__*/React.createElement(_reactNative.Text, {
        style: TextTheme.labelSubtitle
      }, purpose)), s.isSatisfied && selectedCredential !== null && selectedCredential !== void 0 && selectedCredential.requestedAttributes ? renderCard(s, selectedCredential, s.credentials.length > 1) : /*#__PURE__*/React.createElement(_reactNative.Text, {
        style: TextTheme.normal
      }, t('ProofRequest.CredentialNotInWallet')))));
    }));
  };
  const footerButton = (title, buttonPress, buttonType, testID, accessibilityLabel) => {
    return /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.footerButton
    }, /*#__PURE__*/React.createElement(_Button.default, {
      title: title,
      accessibilityLabel: accessibilityLabel,
      testID: testID,
      buttonType: buttonType,
      onPress: buttonPress,
      disabled: !buttonsVisible
    }));
  };
  const footer = () => {
    return /*#__PURE__*/React.createElement(_reactNative.View, {
      style: {
        paddingHorizontal: 25,
        paddingVertical: 16,
        paddingBottom: 26,
        backgroundColor: ColorPallet.brand.secondaryBackground
      }
    }, selectedCredentials && Object.keys(selectedCredentials).length > 0 ? /*#__PURE__*/React.createElement(React.Fragment, null, 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'))) : /*#__PURE__*/React.createElement(React.Fragment, null, footerButton(t('Global.Dismiss'), handleDismiss, _Button.ButtonType.Primary, (0, _testable.testIdWithKey)('DismissCredentialOffer'), t('Global.Dismiss'))));
  };
  return /*#__PURE__*/React.createElement(_ScreenLayout.default, {
    screen: _navigators.Screens.OpenIDCredentialDetails
  }, /*#__PURE__*/React.createElement(_reactNative.ScrollView, null, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.pageContent
  }, renderHeader(), renderBody())), footer(), /*#__PURE__*/React.createElement(_ProofRequestAccept.default, {
    visible: acceptModalVisible,
    proofId: '',
    confirmationOnly: true
  }), /*#__PURE__*/React.createElement(_CommonRemoveModal.default, {
    usage: _remove.ModalUsage.ProofRequestDecline,
    visible: declineModalVisible,
    onSubmit: handleDeclineTouched,
    onCancel: toggleDeclineModalVisible
  }));
};
var _default = exports.default = OpenIDProofPresentation;
//# sourceMappingURL=OpenIDProofPresentation.js.map