import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import { createNetworkMiddleware, checkInternetConnection, offlineActionTypes } from 'react-native-offline';
import rootSaga from '~/lib/saga';
import { reducer } from '~/reducers';
import Rehydration from '~/lib/services/rehydrationServices';
import ReduxPersist from '~/config/ReduxPersist';
import { persistStore, getStoredState } from 'redux-persist';
import AsyncStorage from '@react-native-community/async-storage';
import _ from 'lodash';
import i18n, { updateComponentText } from '~/locale/i18n';
// import { createLogger } from 'redux-logger';
// import {
// 	CHECK_PLAYLIST_STATUS,
// 	START_UPLOAD_TRACKING,
// 	PLAYLIST_PROCESSING_STARTED,
// 	PLAYLIST_PROCESSING_DONE,
// } from '~/store/actionTypes';

const sagaMiddleware = createSagaMiddleware();
const networkMiddleware = createNetworkMiddleware({
	regexActionType: /@request.*/,
	actionTypes: [],
	queueReleaseThrottle: 200,
});

const middlewares = [];
middlewares.push(sagaMiddleware);
middlewares.push(networkMiddleware);

// https://github.com/LogRocket/redux-logger#log-everything-except-actions-with-certain-type
// James Kong 2019-02-14
// fell free to modify if you want to debug redux actions
// if (__DEV__) {
// 	const logger = createLogger({
// 		predicate: (getState, action) => (
// 			action.type === CHECK_PLAYLIST_STATUS ||
// 			action.type === START_UPLOAD_TRACKING ||
// 			action.type === PLAYLIST_PROCESSING_STARTED ||
// 			action.type === PLAYLIST_PROCESSING_DONE
// 		),
// 	});
// 	middlewares.push(logger);
// }
const store = createStore(reducer, applyMiddleware(...middlewares));
const persistor = persistStore(store, {}, async () => {
	// Migrate from previous store to avoid logging out
	const state = store.getState();
	if (state.settings && state.settings.languageCode) {
		i18n.locale = state.settings.languageCode;
		updateComponentText();
	}

	if (!state.user || !state.user.token) {
		// if the user or user token is missing from store
		// we need to populate the user object
		try {
			const { persistConfig } = ReduxPersist;
			// Since we were previously using AsyncStorage, we should get the state using it
			const asyncState = await getStoredState({ ...persistConfig, storage: AsyncStorage });
			if (!_.isEmpty(asyncState)) {
				// use store.dispatch to populate user state
				store.dispatch({ type: 'SUBMIT_LOGIN_SUCCESS', payload: { user: asyncState.user } });
				store.dispatch({ type: 'CHANGE_APP_ROOT', payload: { root: 'main' } });
				// clear the AsyncStorage so it won't cause issues in the future since we use be using
				// file store for storage
				await AsyncStorage.clear();
			}
		} catch (getStateError) {
			// console.warn('getStoredState error', getStateError);
		}
	} else {
		store.dispatch({ type: 'CHANGE_APP_ROOT', payload: { root: 'main' } });
	}
	// Check internet Connection change
	checkInternetConnection()
		.then(isConnected => store.dispatch({
			type: offlineActionTypes.CONNECTION_CHANGE,
			payload: isConnected,
		}));

	// configure persistStore and check reducer version number
	if (ReduxPersist.active) {
		Rehydration.updateReducers();
	}
});

sagaMiddleware.run(rootSaga);

export { store, persistor };
