import { useNavigation, CommonActions } from '@react-navigation/native';
import React, { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { DeviceEventEmitter, StyleSheet } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { EventTypes } from '../constants';
import { TOKENS, useServices } from '../container-api';
import { useAnimatedComponents } from '../contexts/animated-components';
import { useTheme } from '../contexts/theme';
import useInitializeAgent from '../hooks/initialize-agent';
import { BifoldError } from '../types/error';
import { Stacks } from '../types/navigators';
import { useAuth } from '../contexts/auth';

/**
 * 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 {
    walletSecret
  } = useAuth();
  const {
    t
  } = useTranslation();
  const navigation = useNavigation();
  const {
    ColorPallet
  } = useTheme();
  const {
    LoadingIndicator
  } = useAnimatedComponents();
  const {
    initializeAgent
  } = useInitializeAgent();
  const [logger, ocaBundleResolver] = useServices([TOKENS.UTIL_LOGGER, TOKENS.UTIL_OCA_RESOLVER]);
  const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: ColorPallet.brand.primaryBackground
    }
  });
  useEffect(() => {
    const initAgentAsyncEffect = async () => {
      try {
        var _checkForUpdates, _ref;
        await ((_checkForUpdates = (_ref = ocaBundleResolver).checkForUpdates) === null || _checkForUpdates === void 0 ? void 0 : _checkForUpdates.call(_ref));
        if (!walletSecret) {
          throw new Error('Wallet secret is missing');
        }
        const agent = await initializeAgent(walletSecret);
        if (!agent) {
          return;
        }
        navigation.dispatch(CommonActions.reset({
          index: 0,
          routes: [{
            name: Stacks.TabStack
          }]
        }));
      } catch (err) {
        const error = new BifoldError(t('Error.Title1045'), t('Error.Message1045'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1045);
        DeviceEventEmitter.emit(EventTypes.ERROR_ADDED, error);
        logger.error((err === null || err === void 0 ? void 0 : err.message) ?? err);
      }
    };
    initAgentAsyncEffect();
  }, [initializeAgent, ocaBundleResolver, logger, navigation, walletSecret, t]);
  return /*#__PURE__*/React.createElement(SafeAreaView, {
    style: styles.container
  }, /*#__PURE__*/React.createElement(LoadingIndicator, null));
};
export default Splash;
//# sourceMappingURL=Splash.js.map