import ReduxPersist from '~/config/ReduxPersist';
import AsyncStorage from '@react-native-community/async-storage';
import { persistStore } from 'redux-persist';
import { checkInternetConnection } from 'react-native-offline';
// import firebase from 'react-native-firebase';
import { CHECK_USER_TOKEN, GET_GOOGLE_TOKEN } from '~/store/actionTypes';
import { analytics } from '~/lib/utils';
import { store } from '~/store/store';

const dispatchRoute = () => {
	const state = store.getState();
	if (state.user && state.user.token && state.user.token !== '') {
		checkInternetConnection().then(isConnected => {
			if (isConnected) {
				store.dispatch({ type: CHECK_USER_TOKEN, payload: { token: state.user.token } });
				store.dispatch({ type: GET_GOOGLE_TOKEN });
			}
		});
	} else {
		store.dispatch({ type: 'PURGE_STORE' });
	}
};

const initialState = (storage, state) => {
	const {
		users, user, beneficiaries, photos,
	} = state;
	storage.dispatch({
		type: 'PURGE_STORE',
		payload: {
			users, user, beneficiaries, photos,
		},
	});
};

const updateReducers = async () => {
	const { version } = ReduxPersist.persistConfig;
	try {
		// Check to ensure latest reducer version
		const localVersion = await AsyncStorage.getItem('reducerVersion');
		if (localVersion !== version) {
			// Purge store
			const state = store.getState();
			persistStore(store, {}, initialState(store, state)).purge();
			AsyncStorage.setItem('reducerVersion', version);
		} else {
			persistStore(store, {}, dispatchRoute(store));
		}
	} catch (e) {
		persistStore(store, {}, dispatchRoute(store));
		AsyncStorage.setItem('reducerVersion', version);
		analytics.logEvent('error_rehydrate', e);
		// firebase.crashlytics().recordError(e, 'non-fatal');
	}
};

export default { updateReducers };
