import { ProofState } from '@credo-ts/core';
import { useAgent, useProofByState } from '@credo-ts/react-hooks';
import { ProofMetadata } from '@hyperledger/aries-bifold-verifier';
import { useNavigation } from '@react-navigation/core';
import { createStackNavigator } from '@react-navigation/stack';
import { parseUrl } from 'query-string';
import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AppState, DeviceEventEmitter } from 'react-native';
import HeaderButton, { ButtonLocation } from '../components/buttons/HeaderButton';
import { EventTypes, walletTimeout } from '../constants';
import { TOKENS, useContainer } from '../container-api';
import { useAuth } from '../contexts/auth';
import { useConfiguration } from '../contexts/configuration';
import { DispatchAction } from '../contexts/reducers/store';
import { useStore } from '../contexts/store';
import { useTheme } from '../contexts/theme';
import { useDeepLinks } from '../hooks/deep-links';
import Chat from '../screens/Chat';
import { BifoldError } from '../types/error';
import { Screens, Stacks, TabStacks } from '../types/navigators';
import { connectFromInvitation, getOobDeepLink } from '../utils/helpers';
import { testIdWithKey } from '../utils/testable';
import ConnectStack from './ConnectStack';
import ContactStack from './ContactStack';
import DeliveryStack from './DeliveryStack';
import NotificationStack from './NotificationStack';
import ProofRequestStack from './ProofRequestStack';
import SettingStack from './SettingStack';
import TabStack from './TabStack';
import { createDefaultStackOptions } from './defaultStackOptions';
const RootStack = () => {
  const [state, dispatch] = useStore();
  const {
    removeSavedWalletSecret
  } = useAuth();
  const {
    agent
  } = useAgent();
  const appState = useRef(AppState.currentState);
  const [backgroundTime, setBackgroundTime] = useState(undefined);
  const [prevAppStateVisible, setPrevAppStateVisible] = useState('');
  const [appStateVisible, setAppStateVisible] = useState('');
  const {
    t
  } = useTranslation();
  const navigation = useNavigation();
  const theme = useTheme();
  const defaultStackOptions = createDefaultStackOptions(theme);
  const {
    splash,
    enableImplicitInvitations,
    enableReuseConnections,
    enableUseMultUseInvitation
  } = useConfiguration();
  const container = useContainer();
  const OnboardingStack = container.resolve(TOKENS.STACK_ONBOARDING);
  const loadState = container.resolve(TOKENS.LOAD_STATE);
  useDeepLinks();

  // remove connection on mobile verifier proofs if proof is rejected regardless of if it has been opened
  const declinedProofs = useProofByState([ProofState.Declined, ProofState.Abandoned]);
  useEffect(() => {
    declinedProofs.forEach(proof => {
      var _proof$metadata;
      const meta = proof === null || proof === void 0 ? void 0 : (_proof$metadata = proof.metadata) === null || _proof$metadata === void 0 ? void 0 : _proof$metadata.get(ProofMetadata.customMetadata);
      if (meta !== null && meta !== void 0 && meta.delete_conn_after_seen) {
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        agent === null || agent === void 0 ? void 0 : agent.connections.deleteById((proof === null || proof === void 0 ? void 0 : proof.connectionId) ?? '').catch(() => {});
        proof === null || proof === void 0 ? void 0 : proof.metadata.set(ProofMetadata.customMetadata, {
          ...meta,
          delete_conn_after_seen: false
        });
      }
    });
  }, [declinedProofs, state.preferences.useDataRetention]);
  const lockoutUser = async () => {
    if (agent && state.authentication.didAuthenticate) {
      // make sure agent is shutdown so wallet isn't still open
      removeSavedWalletSecret();
      try {
        await agent.wallet.close();
        await agent.shutdown();
      } catch (error) {
        var _agent$config, _agent$config$logger;
        agent === null || agent === void 0 ? void 0 : (_agent$config = agent.config) === null || _agent$config === void 0 ? void 0 : (_agent$config$logger = _agent$config.logger) === null || _agent$config$logger === void 0 ? void 0 : _agent$config$logger.error(`Error shutting down agent: ${error}`);
      }
      dispatch({
        type: DispatchAction.DID_AUTHENTICATE,
        payload: [{
          didAuthenticate: false
        }]
      });
      dispatch({
        type: DispatchAction.LOCKOUT_UPDATED,
        payload: [{
          displayNotification: true
        }]
      });
    }
  };
  useEffect(() => {
    loadState(dispatch).then(() => {
      dispatch({
        type: DispatchAction.STATE_LOADED
      });
    }).catch(err => {
      const error = new BifoldError(t('Error.Title1044'), t('Error.Message1044'), err.message, 1001);
      DeviceEventEmitter.emit(EventTypes.ERROR_ADDED, error);
    });
  }, []);

  // handle deeplink events
  useEffect(() => {
    async function handleDeepLink(deepLink) {
      // If it's just the general link with no params, set link inactive and do nothing
      if (deepLink.endsWith('//')) {
        dispatch({
          type: DispatchAction.ACTIVE_DEEP_LINK,
          payload: [undefined]
        });
        return;
      }
      try {
        var _receivedInvitation$c;
        // Try connection based
        const receivedInvitation = await connectFromInvitation(deepLink, agent, enableImplicitInvitations, enableReuseConnections, enableUseMultUseInvitation);
        navigation.navigate(Stacks.ConnectionStack, {
          screen: Screens.Connection,
          params: {
            connectionId: receivedInvitation === null || receivedInvitation === void 0 ? void 0 : (_receivedInvitation$c = receivedInvitation.connectionRecord) === null || _receivedInvitation$c === void 0 ? void 0 : _receivedInvitation$c.id
          }
        });
      } catch {
        try {
          // Try connectionless here
          const queryParams = parseUrl(deepLink).query;
          const param = queryParams['d_m'] ?? queryParams['c_i'];
          // if missing both of the required params, don't attempt to open OOB
          if (!param) {
            dispatch({
              type: DispatchAction.ACTIVE_DEEP_LINK,
              payload: [undefined]
            });
            return;
          }
          const message = await getOobDeepLink(deepLink, agent);
          navigation.navigate(Stacks.ConnectionStack, {
            screen: Screens.Connection,
            params: {
              threadId: message['@id']
            }
          });
        } catch (err) {
          const error = new BifoldError(t('Error.Title1039'), t('Error.Message1039'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1039);
          DeviceEventEmitter.emit(EventTypes.ERROR_ADDED, error);
        }
      }

      // set deeplink as inactive
      dispatch({
        type: DispatchAction.ACTIVE_DEEP_LINK,
        payload: [undefined]
      });
    }
    if (agent && state.deepLink.activeDeepLink && state.authentication.didAuthenticate) {
      handleDeepLink(state.deepLink.activeDeepLink);
    }
  }, [agent, state.deepLink.activeDeepLink, state.authentication.didAuthenticate]);
  useEffect(() => {
    AppState.addEventListener('change', nextAppState => {
      if (appState.current.match(/active/) && nextAppState.match(/inactive|background/)) {
        //update time that app gets put in background
        setBackgroundTime(Date.now());
      }
      setPrevAppStateVisible(appState.current);
      appState.current = nextAppState;
      setAppStateVisible(appState.current);
    });
  }, []);
  useEffect(() => {
    if (appStateVisible.match(/active/) && prevAppStateVisible.match(/inactive|background/) && backgroundTime) {
      // prevents the user from being locked out during metro reloading
      setPrevAppStateVisible(appStateVisible);
      //lock user out after 5 minutes
      if (!state.preferences.preventAutoLock && walletTimeout && backgroundTime && Date.now() - backgroundTime > walletTimeout) {
        lockoutUser();
      }
    }
  }, [appStateVisible, prevAppStateVisible, backgroundTime]);

  // auth stack should now be in the OnboardingStack

  const mainStack = () => {
    const Stack = createStackNavigator();

    // This function is to make the fade in behavior of both iOS and Android consistent for the settings menu
    const forFade = _ref => {
      let {
        current
      } = _ref;
      return {
        cardStyle: {
          opacity: current.progress
        }
      };
    };
    return /*#__PURE__*/React.createElement(Stack.Navigator, {
      initialRouteName: Screens.Splash,
      screenOptions: {
        ...defaultStackOptions,
        headerShown: false
      }
    }, /*#__PURE__*/React.createElement(Stack.Screen, {
      name: Screens.Splash,
      component: splash
    }), /*#__PURE__*/React.createElement(Stack.Screen, {
      name: Stacks.TabStack,
      component: TabStack
    }), /*#__PURE__*/React.createElement(Stack.Screen, {
      name: Screens.Chat,
      component: Chat,
      options: _ref2 => {
        let {
          navigation
        } = _ref2;
        return {
          headerShown: true,
          title: t('Screens.CredentialOffer'),
          headerLeft: () => /*#__PURE__*/React.createElement(HeaderButton, {
            buttonLocation: ButtonLocation.Left,
            accessibilityLabel: t('Global.Back'),
            testID: testIdWithKey('BackButton'),
            onPress: () => {
              navigation.navigate(TabStacks.HomeStack, {
                screen: Screens.Home
              });
            },
            icon: "arrow-left"
          })
        };
      }
    }), /*#__PURE__*/React.createElement(Stack.Screen, {
      name: Stacks.ConnectStack,
      component: ConnectStack
    }), /*#__PURE__*/React.createElement(Stack.Screen, {
      name: Stacks.SettingStack,
      component: SettingStack,
      options: {
        cardStyleInterpolator: forFade
      }
    }), /*#__PURE__*/React.createElement(Stack.Screen, {
      name: Stacks.ContactStack,
      component: ContactStack
    }), /*#__PURE__*/React.createElement(Stack.Screen, {
      name: Stacks.NotificationStack,
      component: NotificationStack
    }), /*#__PURE__*/React.createElement(Stack.Screen, {
      name: Stacks.ConnectionStack,
      component: DeliveryStack,
      options: {
        gestureEnabled: false
      }
    }), /*#__PURE__*/React.createElement(Stack.Screen, {
      name: Stacks.ProofRequestsStack,
      component: ProofRequestStack
    }));
  };
  if ((state.onboarding.onboardingVersion !== 0 && state.onboarding.didCompleteOnboarding || state.onboarding.onboardingVersion === 0 && state.onboarding.didConsiderBiometry) && state.authentication.didAuthenticate && state.onboarding.postAuthScreens.length === 0) {
    return mainStack();
  }
  return /*#__PURE__*/React.createElement(OnboardingStack, null);
};
export default RootStack;
//# sourceMappingURL=RootStack.js.map