"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useOpenID = void 0;
var _react = require("react");
var _reactNative = require("react-native");
var _constants = require("../../../constants");
var _error = require("../../../types/error");
var _reactHooks = require("@credo-ts/react-hooks");
var _reactI18next = require("react-i18next");
var _resolverProof = require("../resolverProof");
var _offerResolve = require("../offerResolve");
const useOpenID = ({
  openIDUri,
  openIDPresentationUri
}) => {
  const [openIdRecord, setOpenIdRecord] = (0, _react.useState)();
  const {
    agent
  } = (0, _reactHooks.useAgent)();
  const {
    t
  } = (0, _reactI18next.useTranslation)();
  const resolveOpenIDCredential = (0, _react.useCallback)(async uri => {
    if (!agent) {
      return;
    }
    try {
      const resolvedCredentialOffer = await (0, _offerResolve.resolveOpenId4VciOffer)({
        agent: agent,
        uri: uri
      });
      const tokenResponse = await (0, _offerResolve.acquirePreAuthorizedAccessToken)({
        agent,
        resolvedCredentialOffer
      });
      return await (0, _offerResolve.receiveCredentialFromOpenId4VciOffer)({
        agent,
        resolvedCredentialOffer,
        accessToken: tokenResponse
      });
    } catch (err) {
      //TODO: Sppecify different error
      const error = new _error.BifoldError(t('Error.Title1024'), t('Error.Message1024'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1043);
      _reactNative.DeviceEventEmitter.emit(_constants.EventTypes.ERROR_ADDED, error);
    }
  }, [agent, t]);
  const resolveOpenIDPresentationRequest = (0, _react.useCallback)(async uri => {
    if (!agent) {
      return;
    }
    try {
      const record = await (0, _resolverProof.getCredentialsForProofRequest)({
        agent: agent,
        uri: uri
      });
      return record;
    } catch (err) {
      const error = new _error.BifoldError(t('Error.Title1043'), t('Error.Message1043'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1043);
      _reactNative.DeviceEventEmitter.emit(_constants.EventTypes.ERROR_ADDED, error);
    }
  }, [agent, t]);
  (0, _react.useEffect)(() => {
    if (!openIDPresentationUri) {
      return;
    }
    resolveOpenIDPresentationRequest(openIDPresentationUri).then(value => {
      if (value) {
        setOpenIdRecord(value);
      }
    });
  }, [openIDPresentationUri, resolveOpenIDPresentationRequest]);
  (0, _react.useEffect)(() => {
    if (!openIDUri) {
      return;
    }
    resolveOpenIDCredential(openIDUri).then(value => {
      if (value) {
        setOpenIdRecord(value);
      }
    });
  }, [openIDUri, resolveOpenIDCredential]);
  return openIdRecord;
};
exports.useOpenID = useOpenID;
//# sourceMappingURL=openid.js.map