import { createStore, applyMiddleware, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';

import { persistStore, persistCombineReducers } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

import { i18nReducer, syncTranslationWithStore } from 'react-redux-i18n';

import { getConf } from './configuration';

import combinedReducers from './Reducers';
import deviceReducer from './Reducers/Device/Reducer';
import apiReducer from './Reducers/Reducer';

import { setInitialState } from './Reducers/GeneralActions';

const reduxPersistConfig = getConf('reduxPersist', { enabled: false });

let rootReducer;

// adding core reducers
const reducers = {
    ...combinedReducers,
    i18n: i18nReducer,
    device: deviceReducer,
    api: apiReducer,
};

if (reduxPersistConfig.enabled && 'storeConfig' in reduxPersistConfig) {
    const persistConfig = {
        key: 'root',
        storage,
        ...reduxPersistConfig.storeConfig,
    };

    rootReducer = persistCombineReducers(persistConfig, reducers);
} else {
    rootReducer = combineReducers(reducers);
}

const middleware = [thunk];
if (process.env.NODE_ENV === 'development') {
    middleware.push(createLogger());
}

export function createAppStore() {
    return createStore(rootReducer, applyMiddleware(...middleware));
}

export const store = createAppStore();

if (reduxPersistConfig.enabled) {
    persistStore(store);
}

// the first action to set the initial states (in the custom project)
store.dispatch(setInitialState());

// translation setup
syncTranslationWithStore(store);

export default store;
