import { combineReducers, configureStore } from '@reduxjs/toolkit';
import { prayerCircle } from '../PrayerCircle/prayerCircleSlice';
import { NativeStoragePromise } from 'cordova-sites';
import { persistReducer, persistStore, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER } from 'redux-persist';
import { settings } from '../Settings/settingsSlice';

const reducers = combineReducers({
    prayerCircle,
    settings,
});

const persistConfig = {
    key: 'redux-store',
    version: 1,
    storage: NativeStoragePromise,
};

const persistedReducer = persistReducer(persistConfig, reducers);

export const store = configureStore({
    reducer: persistedReducer,
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: { ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER] },
        }),
});

// let saveTimeout: TimeoutId | undefined;
// store.subscribe(() => {
//     if (!saveTimeout) {
//         saveTimeout = setTimeout(async () => {
//             saveTimeout = undefined;
//             const data = store.getState();
//             await NativeStoragePromise.setItem(`store-data`, data);
//         }, 500);
//     }
// });
export const persistor = persistStore(store);

export type StoreState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
