"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useOpenIDCredentials = exports.OpenIDCredentialRecordProvider = void 0;
var _react = require("react");
var _core = require("@credo-ts/core");
var _reactHooks = require("@credo-ts/react-hooks");
var _recordUtils = require("@credo-ts/react-hooks/build/recordUtils");
var _containerApi = require("../../../container-api");
const addRecord = (record, state) => {
  const newRecordsState = [...state.w3cCredentialRecords];
  newRecordsState.unshift(record);
  return {
    ...state,
    w3cCredentialRecords: newRecordsState
  };
};
const removeRecord = (record, state) => {
  const newRecordsState = [...state.w3cCredentialRecords];
  const index = newRecordsState.findIndex(r => r.id === record.id);
  if (index > -1) {
    newRecordsState.splice(index, 1);
  }
  return {
    ...state,
    w3cCredentialRecords: newRecordsState
  };
};
const defaultState = {
  openIDCredentialRecords: [],
  w3cCredentialRecords: [],
  sdJwtVcRecords: [],
  isLoading: true
};
const OpenIDCredentialRecordContext = /*#__PURE__*/(0, _react.createContext)(null);
const isW3CCredentialRecord = record => {
  var _record$getTags;
  return ((_record$getTags = record.getTags()) === null || _record$getTags === void 0 ? void 0 : _record$getTags.claimFormat) === _core.ClaimFormat.JwtVc;
};
const filterW3CCredentialsOnly = credentials => {
  return credentials.filter(r => isW3CCredentialRecord(r));
};

// eslint-disable-next-line react/prop-types
const OpenIDCredentialRecordProvider = ({
  children
}) => {
  const [state, setState] = (0, _react.useState)(defaultState);
  const {
    agent
  } = (0, _reactHooks.useAgent)();
  const [logger] = (0, _containerApi.useServices)([_containerApi.TOKENS.UTIL_LOGGER]);
  function checkAgent() {
    if (!agent) {
      const error = 'Agent undefined!';
      logger.error(`[OpenIDCredentialRecordProvider] ${error}`);
      throw new Error(error);
    }
  }
  async function getCredentialById(id) {
    checkAgent();
    return await (agent === null || agent === void 0 ? void 0 : agent.w3cCredentials.getCredentialRecordById(id));
  }
  async function storeCredential(cred) {
    checkAgent();
    if (cred instanceof _core.W3cCredentialRecord) {
      await (agent === null || agent === void 0 ? void 0 : agent.dependencyManager.resolve(_core.W3cCredentialRepository).save(agent.context, cred));
    } else {
      await (agent === null || agent === void 0 ? void 0 : agent.dependencyManager.resolve(_core.SdJwtVcRepository).save(agent.context, cred));
    }
  }
  async function deleteCredential(cred) {
    checkAgent();
    if (cred instanceof _core.W3cCredentialRecord) {
      await (agent === null || agent === void 0 ? void 0 : agent.w3cCredentials.removeCredentialRecord(cred.id));
    } else if (cred instanceof _core.SdJwtVcRecord) {
      await (agent === null || agent === void 0 ? void 0 : agent.sdJwtVc.deleteById(cred.id));
    }
  }
  (0, _react.useEffect)(() => {
    var _agent$w3cCredentials;
    if (!agent) {
      return;
    }
    (_agent$w3cCredentials = agent.w3cCredentials) === null || _agent$w3cCredentials === void 0 || _agent$w3cCredentials.getAllCredentialRecords().then(w3cCredentialRecords => {
      setState(prev => ({
        ...prev,
        w3cCredentialRecords: filterW3CCredentialsOnly(w3cCredentialRecords),
        isLoading: false
      }));
    });
  }, [agent]);
  (0, _react.useEffect)(() => {
    if (!state.isLoading && agent) {
      const credentialAdded$ = (0, _recordUtils.recordsAddedByType)(agent, _core.W3cCredentialRecord).subscribe(record => {
        //This handler will return ANY creds added to the wallet even DidComm
        //Sounds like a bug in the hooks package
        //This check will safe guard the flow untill a fix goes to the hooks
        if (isW3CCredentialRecord(record)) {
          setState(addRecord(record, state));
        }
      });
      const credentialRemoved$ = (0, _recordUtils.recordsRemovedByType)(agent, _core.W3cCredentialRecord).subscribe(record => {
        setState(removeRecord(record, state));
      });
      return () => {
        credentialAdded$.unsubscribe();
        credentialRemoved$.unsubscribe();
      };
    }
  }, [state, agent]);
  return /*#__PURE__*/React.createElement(OpenIDCredentialRecordContext.Provider, {
    value: {
      openIdState: state,
      storeCredential: storeCredential,
      removeCredential: deleteCredential,
      getCredentialById: getCredentialById
    }
  }, children);
};
exports.OpenIDCredentialRecordProvider = OpenIDCredentialRecordProvider;
const useOpenIDCredentials = () => (0, _react.useContext)(OpenIDCredentialRecordContext);
exports.useOpenIDCredentials = useOpenIDCredentials;
//# sourceMappingURL=OpenIDCredentialRecordProvider.js.map