"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _native = require("@react-navigation/native");
var _react = _interopRequireWildcard(require("react"));
var _reactI18next = require("react-i18next");
var _reactNative = require("react-native");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
var _constants = require("../constants");
var _containerApi = require("../container-api");
var _animatedComponents = require("../contexts/animated-components");
var _store = require("../contexts/reducers/store");
var _store2 = require("../contexts/store");
var _theme = require("../contexts/theme");
var _initializeAgent = _interopRequireDefault(require("../hooks/initialize-agent"));
var _error = require("../types/error");
var _navigators = require("../types/navigators");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
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; }
const OnboardingVersion = 1;
const onboardingComplete = (onboardingVersion, didCompleteOnboarding, didConsiderBiometry) => {
  return onboardingVersion !== 0 && didCompleteOnboarding || onboardingVersion === 0 && didConsiderBiometry;
};
const resumeOnboardingAt = (didSeePreface, didCompleteTutorial, didAgreeToTerms, didCreatePIN, didNameWallet, didConsiderBiometry, termsVersion, enableWalletNaming, showPreface) => {
  const termsVer = termsVersion ?? true;
  if ((didSeePreface || !showPreface) && didCompleteTutorial && didAgreeToTerms === termsVer && didCreatePIN && (didNameWallet || !enableWalletNaming) && !didConsiderBiometry) {
    return _navigators.Screens.UseBiometry;
  }
  if ((didSeePreface || !showPreface) && didCompleteTutorial && didAgreeToTerms === termsVer && didCreatePIN && enableWalletNaming && !didNameWallet) {
    return _navigators.Screens.NameWallet;
  }
  if ((didSeePreface || !showPreface) && didCompleteTutorial && didAgreeToTerms === termsVer && !didCreatePIN) {
    return _navigators.Screens.CreatePIN;
  }
  if ((didSeePreface || !showPreface) && didCompleteTutorial && !didAgreeToTerms) {
    return _navigators.Screens.Terms;
  }
  if (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 {
    t
  } = (0, _reactI18next.useTranslation)();
  const [store, dispatch] = (0, _store2.useStore)();
  const navigation = (0, _native.useNavigation)();
  const {
    ColorPallet
  } = (0, _theme.useTheme)();
  const {
    LoadingIndicator
  } = (0, _animatedComponents.useAnimatedComponents)();
  const [mounted, setMounted] = (0, _react.useState)(false);
  const initializing = (0, _react.useRef)(false);
  const {
    initializeAgent
  } = (0, _initializeAgent.default)();
  const [{
    version: TermsVersion
  }, logger, {
    showPreface,
    enablePushNotifications
  }, ocaBundleResolver, historyEnabled] = (0, _containerApi.useServices)([_containerApi.TOKENS.SCREEN_TERMS, _containerApi.TOKENS.UTIL_LOGGER, _containerApi.TOKENS.CONFIG, _containerApi.TOKENS.UTIL_OCA_RESOLVER, _containerApi.TOKENS.HISTORY_ENABLED]);
  const styles = _reactNative.StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: ColorPallet.brand.primaryBackground
    }
  });

  // navigation calls that occur before the screen is fully mounted will fail
  // this useeffect prevents that race condition
  (0, _react.useEffect)(() => {
    setMounted(true);
  }, []);
  (0, _react.useEffect)(() => {
    if (!mounted || store.authentication.didAuthenticate || !store.stateLoaded) {
      return;
    }
    try {
      if (store.onboarding.onboardingVersion !== OnboardingVersion) {
        dispatch({
          type: _store.DispatchAction.ONBOARDING_VERSION,
          payload: [OnboardingVersion]
        });
        return;
      }
      if (!onboardingComplete(store.onboarding.onboardingVersion, store.onboarding.didCompleteOnboarding, store.onboarding.didConsiderBiometry)) {
        // If onboarding was interrupted we need to pickup from where we left off.
        navigation.dispatch(_native.CommonActions.reset({
          index: 0,
          routes: [{
            name: resumeOnboardingAt(store.onboarding.didSeePreface, store.onboarding.didCompleteTutorial, store.onboarding.didAgreeToTerms, store.onboarding.didCreatePIN, store.onboarding.didNameWallet, store.onboarding.didConsiderBiometry, TermsVersion, store.preferences.enableWalletNaming, showPreface)
          }]
        }));
        return;
      }
      if (store.onboarding.onboardingVersion !== OnboardingVersion) {
        dispatch({
          type: _store.DispatchAction.ONBOARDING_VERSION,
          payload: [OnboardingVersion]
        });
        return;
      }

      // 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]
        });
        return;
      }

      // if they previously completed onboarding before preface was enabled, mark seen
      if (!store.onboarding.didSeePreface) {
        dispatch({
          type: _store.DispatchAction.DID_SEE_PREFACE
        });
        return;
      }

      // add post authentication screens
      const postAuthScreens = [];
      if (store.onboarding.didAgreeToTerms !== TermsVersion) {
        postAuthScreens.push(_navigators.Screens.Terms);
      }
      if (!store.onboarding.didConsiderPushNotifications && enablePushNotifications) {
        postAuthScreens.push(_navigators.Screens.UsePushNotifications);
      }
      dispatch({
        type: _store.DispatchAction.SET_POST_AUTH_SCREENS,
        payload: [postAuthScreens]
      });
      if (!store.loginAttempt.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
          }]
        }));
      }
    } catch (err) {
      const error = new _error.BifoldError(t('Error.Title1044'), t('Error.Message1044'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1044);
      _reactNative.DeviceEventEmitter.emit(_constants.EventTypes.ERROR_ADDED, error);
      logger.error((err === null || err === void 0 ? void 0 : err.message) ?? err);
    }
  }, [mounted, store.authentication.didAuthenticate, store.stateLoaded, store.onboarding.onboardingVersion, store.onboarding.didCompleteOnboarding, store.onboarding.didSeePreface, store.onboarding.didCompleteTutorial, store.onboarding.didAgreeToTerms, store.onboarding.didCreatePIN, store.onboarding.didConsiderPushNotifications, store.onboarding.didNameWallet, store.onboarding.didConsiderBiometry, store.preferences.enableWalletNaming, enablePushNotifications, TermsVersion, showPreface, dispatch, store.loginAttempt.lockoutDate, navigation, t, logger]);
  (0, _react.useEffect)(() => {
    const initAgentAsyncEffect = async () => {
      try {
        var _checkForUpdates, _ref;
        if (!mounted || initializing.current || !store.authentication.didAuthenticate || !store.onboarding.didConsiderBiometry) {
          return;
        }
        initializing.current = true;
        await ((_checkForUpdates = (_ref = ocaBundleResolver).checkForUpdates) === null || _checkForUpdates === void 0 ? void 0 : _checkForUpdates.call(_ref));
        const agent = await initializeAgent();
        if (!agent) {
          initializing.current = false;
          return;
        }
        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);
        _reactNative.DeviceEventEmitter.emit(_constants.EventTypes.ERROR_ADDED, error);
        logger.error((err === null || err === void 0 ? void 0 : err.message) ?? err);
      }
    };
    initAgentAsyncEffect();
  }, [initializeAgent, mounted, store.authentication.didAuthenticate, store.onboarding.didConsiderBiometry, store.onboarding.postAuthScreens.length, ocaBundleResolver, logger, navigation, t]);
  (0, _react.useEffect)(() => {
    if (!mounted || !historyEnabled) {
      return;
    }
    dispatch({
      type: _store.DispatchAction.HISTORY_CAPABILITY,
      payload: [true]
    });
  }, [mounted, historyEnabled, dispatch]);
  return /*#__PURE__*/_react.default.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
    style: styles.container
  }, /*#__PURE__*/_react.default.createElement(LoadingIndicator, null));
};
var _default = exports.default = Splash;
//# sourceMappingURL=Splash.js.map