"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _core = require("@aries-framework/core");
var _reactHooks = require("@aries-framework/react-hooks");
var _reactNative = require("@aries-framework/react-native");
var _asyncStorage = _interopRequireDefault(require("@react-native-async-storage/async-storage"));
var _core2 = require("@react-navigation/core");
var _native = require("@react-navigation/native");
var _react = _interopRequireWildcard(require("react"));
var _reactI18next = require("react-i18next");
var _reactNative2 = require("react-native");
var _reactNativeConfig = require("react-native-config");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
var _constants = require("../constants");
var _animatedComponents = require("../contexts/animated-components");
var _auth = require("../contexts/auth");
var _configuration = require("../contexts/configuration");
var _store = require("../contexts/reducers/store");
var _store2 = require("../contexts/store");
var _theme = require("../contexts/theme");
var _keychain = require("../services/keychain");
var _error = require("../types/error");
var _navigators = require("../types/navigators");
var _agent = require("../utils/agent");
var _migration = require("../utils/migration");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const onboardingComplete = state => {
  return state.didCompleteTutorial && state.didAgreeToTerms && state.didCreatePIN && state.didConsiderBiometry;
};
const resumeOnboardingAt = (state, enableWalletNaming, showPreface) => {
  if ((state.didSeePreface || !showPreface) && state.didCompleteTutorial && state.didAgreeToTerms && state.didCreatePIN && (state.didNameWallet || !enableWalletNaming) && !state.didConsiderBiometry) {
    return _navigators.Screens.UseBiometry;
  }
  if ((state.didSeePreface || !showPreface) && state.didCompleteTutorial && state.didAgreeToTerms && state.didCreatePIN && enableWalletNaming && !state.didNameWallet) {
    return _navigators.Screens.NameWallet;
  }
  if ((state.didSeePreface || !showPreface) && state.didCompleteTutorial && state.didAgreeToTerms && !state.didCreatePIN) {
    return _navigators.Screens.CreatePIN;
  }
  if ((state.didSeePreface || !showPreface) && state.didCompleteTutorial && !state.didAgreeToTerms) {
    return _navigators.Screens.Terms;
  }
  if (state.didSeePreface || !showPreface) {
    return _navigators.Screens.Onboarding;
  }
  return _navigators.Screens.Preface;
};

/**
 * To customize this splash screen set the background color of the
 * iOS and Android launch screen to match the background color of
 * of this view.
 */
const Splash = () => {
  const {
    indyLedgers,
    showPreface
  } = (0, _configuration.useConfiguration)();
  const {
    setAgent
  } = (0, _reactHooks.useAgent)();
  const {
    t
  } = (0, _reactI18next.useTranslation)();
  const [store, dispatch] = (0, _store2.useStore)();
  const navigation = (0, _core2.useNavigation)();
  const {
    getWalletCredentials
  } = (0, _auth.useAuth)();
  const {
    ColorPallet
  } = (0, _theme.useTheme)();
  const {
    LoadingIndicator
  } = (0, _animatedComponents.useAnimatedComponents)();
  const styles = _reactNative2.StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: ColorPallet.brand.primaryBackground
    }
  });
  const loadAuthAttempts = async () => {
    const attempts = await (0, _keychain.loadLoginAttempt)();
    if (attempts) {
      dispatch({
        type: _store.DispatchAction.ATTEMPT_UPDATED,
        payload: [attempts]
      });
      return attempts;
    }
  };
  (0, _react.useEffect)(() => {
    if (store.authentication.didAuthenticate) {
      return;
    }
    const initOnboarding = async () => {
      try {
        // load authentication attempts from storage
        const attemptData = await loadAuthAttempts();
        const preferencesData = await _asyncStorage.default.getItem(_constants.LocalStorageKeys.Preferences);
        if (preferencesData) {
          const dataAsJSON = JSON.parse(preferencesData);
          dispatch({
            type: _store.DispatchAction.PREFERENCES_UPDATED,
            payload: [dataAsJSON]
          });
        }
        const migrationData = await _asyncStorage.default.getItem(_constants.LocalStorageKeys.Migration);
        if (migrationData) {
          const dataAsJSON = JSON.parse(migrationData);
          dispatch({
            type: _store.DispatchAction.MIGRATION_UPDATED,
            payload: [dataAsJSON]
          });
        }
        const toursData = await _asyncStorage.default.getItem(_constants.LocalStorageKeys.Tours);
        if (toursData) {
          const dataAsJSON = JSON.parse(toursData);
          dispatch({
            type: _store.DispatchAction.TOUR_DATA_UPDATED,
            payload: [dataAsJSON]
          });
        }
        const data = await _asyncStorage.default.getItem(_constants.LocalStorageKeys.Onboarding);
        if (data) {
          const onboardingState = JSON.parse(data);
          dispatch({
            type: _store.DispatchAction.ONBOARDING_UPDATED,
            payload: [onboardingState]
          });
          if (onboardingComplete(onboardingState)) {
            // if they previously completed onboarding before wallet naming was enabled, mark complete
            if (!store.onboarding.didNameWallet) {
              dispatch({
                type: _store.DispatchAction.DID_NAME_WALLET,
                payload: [true]
              });
            }

            // if they previously completed onboarding before preface was enabled, mark seen
            if (!store.onboarding.didSeePreface) {
              dispatch({
                type: _store.DispatchAction.DID_SEE_PREFACE
              });
            }
            if (!(attemptData !== null && attemptData !== void 0 && attemptData.lockoutDate)) {
              navigation.dispatch(_native.CommonActions.reset({
                index: 0,
                routes: [{
                  name: _navigators.Screens.EnterPIN
                }]
              }));
            } else {
              // return to lockout screen if lockout date is set
              navigation.dispatch(_native.CommonActions.reset({
                index: 0,
                routes: [{
                  name: _navigators.Screens.AttemptLockout
                }]
              }));
            }
            return;
          } else {
            // If onboarding was interrupted we need to pickup from where we left off.
            navigation.dispatch(_native.CommonActions.reset({
              index: 0,
              routes: [{
                name: resumeOnboardingAt(onboardingState, store.preferences.enableWalletNaming, showPreface)
              }]
            }));
          }
          return;
        }
        // We have no onboarding state, starting from step zero.
        if (showPreface) {
          navigation.dispatch(_native.CommonActions.reset({
            index: 0,
            routes: [{
              name: _navigators.Screens.Preface
            }]
          }));
        } else {
          navigation.dispatch(_native.CommonActions.reset({
            index: 0,
            routes: [{
              name: _navigators.Screens.Onboarding
            }]
          }));
        }
      } catch (err) {
        const error = new _error.BifoldError(t('Error.Title1044'), t('Error.Message1044'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1044);
        _reactNative2.DeviceEventEmitter.emit(_constants.EventTypes.ERROR_ADDED, error);
      }
    };
    initOnboarding();
  }, [store.authentication.didAuthenticate]);
  (0, _react.useEffect)(() => {
    if (!store.authentication.didAuthenticate || !store.onboarding.didConsiderBiometry) {
      return;
    }
    const initAgent = async () => {
      try {
        const credentials = await getWalletCredentials();
        if (!(credentials !== null && credentials !== void 0 && credentials.id) || !credentials.key) {
          // Cannot find wallet id/secret
          return;
        }
        const newAgent = new _core.Agent({
          config: {
            label: store.preferences.walletName || 'Aries Bifold',
            walletConfig: {
              id: credentials.id,
              key: credentials.key
            },
            logger: new _core.ConsoleLogger(_core.LogLevel.trace),
            autoUpdateStorageOnStartup: true
          },
          dependencies: _reactNative.agentDependencies,
          modules: (0, _agent.getAgentModules)({
            indyNetworks: indyLedgers,
            mediatorInvitationUrl: _reactNativeConfig.Config.MEDIATOR_URL
          })
        });
        const wsTransport = new _core.WsOutboundTransport();
        const httpTransport = new _core.HttpOutboundTransport();
        newAgent.registerOutboundTransport(wsTransport);
        newAgent.registerOutboundTransport(httpTransport);

        // If we haven't migrated to Aries Askar yet, we need to do this before we initialize the agent.
        if (!(0, _migration.didMigrateToAskar)(store.migration)) {
          newAgent.config.logger.debug('Agent not updated to Aries Askar, updating...');
          await (0, _migration.migrateToAskar)(credentials.id, credentials.key, newAgent);
          newAgent.config.logger.debug('Successfully finished updating agent to Aries Askar');
          // Store that we migrated to askar.
          dispatch({
            type: _store.DispatchAction.DID_MIGRATE_TO_ASKAR
          });
        }
        await newAgent.initialize();
        await (0, _agent.createLinkSecretIfRequired)(newAgent);
        setAgent(newAgent);
        navigation.dispatch(_native.CommonActions.reset({
          index: 0,
          routes: [{
            name: _navigators.Stacks.TabStack
          }]
        }));
      } catch (err) {
        const error = new _error.BifoldError(t('Error.Title1045'), t('Error.Message1045'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1045);
        _reactNative2.DeviceEventEmitter.emit(_constants.EventTypes.ERROR_ADDED, error);
      }
    };
    initAgent();
  }, [store.authentication.didAuthenticate, store.onboarding.didConsiderBiometry]);
  return /*#__PURE__*/_react.default.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
    style: styles.container
  }, /*#__PURE__*/_react.default.createElement(LoadingIndicator, null));
};
var _default = Splash;
exports.default = _default;
//# sourceMappingURL=Splash.js.map