import * as _ from 'lodash-es';
import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import createSagaMiddleware from 'redux-saga';
import { fork } from 'redux-saga/effects';
import answersReducer from './answers/reducer';
import answersSaga from './answers/sagas';
import audioReducer from './audio/reducer';
import audioSaga from './audio/sagas';
import casReducer from './cas/reducer';
import casSaga from './cas/sagas';
import { validateAnswers } from '../validateAnswers';
const rootReducer = combineReducers({
    answers: answersReducer,
    audio: audioReducer,
    cas: casReducer
});
function* rootSaga(examServerApi) {
    yield fork(answersSaga, examServerApi);
    yield fork(audioSaga, examServerApi);
    yield fork(casSaga, examServerApi);
}
export function initializeExamStore(examStructure, casStatus, initialAnswers, restrictedAudioPlaybackStats, examServerApi) {
    const initialQuestionIds = new Set(_.map(initialAnswers, 'questionId'));
    const playbackTimes = _.mapValues(_.keyBy(restrictedAudioPlaybackStats, 'restrictedAudioId'), 'times');
    const answersById = _.keyBy(initialAnswers, 'questionId');
    const initialState = {
        answers: {
            answersById,
            focusedQuestionId: null,
            serverQuestionIds: initialQuestionIds,
            supportsAnswerHistory: typeof examServerApi.selectAnswerVersion === 'function',
            savedQuestionIds: initialQuestionIds,
            examStructure,
            validationErrors: validateAnswers(examStructure, answersById)
        },
        audio: {
            errors: {},
            nowPlaying: null,
            playbackTimes
        },
        cas: { casStatus }
    };
    const sagaMiddleware = createSagaMiddleware({
        onError(error, errorInfo) {
            var _a;
            console.error('Uncaught saga error', error, errorInfo.sagaStack);
            (_a = examServerApi.onFatalError) === null || _a === void 0 ? void 0 : _a.call(examServerApi, error);
        }
    });
    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
    const enhancers = composeEnhancers(applyMiddleware(sagaMiddleware));
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    const store = createStore(rootReducer, initialState, enhancers);
    sagaMiddleware.run(rootSaga, examServerApi);
    return store;
}
//# sourceMappingURL=index.js.map