import { call, cancel, delay, fork, put, take } from 'redux-saga/effects';
import { saveAnswer, saveAnswerFailed, saveAnswerSucceeded } from './actions';
const tasks = new Map();
function* performSave(action, examServerApi) {
    const answer = action.payload;
    try {
        yield delay(1000);
        yield call(examServerApi.saveAnswer, answer);
        yield put(saveAnswerSucceeded(answer));
    }
    catch (error) {
        console.error('Perform save failed', error);
        yield put(saveAnswerFailed(answer, error));
    }
    tasks.delete(answer.questionId);
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function* answersSaga(examServerApi) {
    // Approximate takeLatest, except grouped by question id.
    // https://redux-saga.js.org/docs/api/#takelatestpattern-saga-args
    while (true) {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        const action = yield take('SAVE_ANSWER');
        const existing = tasks.get(action.payload.questionId);
        if (existing) {
            yield cancel(existing);
        }
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        const task = yield fork(performSave, action, examServerApi);
        tasks.set(action.payload.questionId, task);
    }
}
function* answerHistorySaga(examServerApi) {
    while (examServerApi.selectAnswerVersion) {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        const action = yield take('SELECT_ANSWER_VERSION');
        const { questionId, questionText } = action.payload;
        if (examServerApi.logActivity) {
            try {
                yield call(examServerApi.logActivity, `Opened answer version history for question ${questionId}, ${questionText}`);
            }
            catch (error) {
                console.error('Logging activity failed', error);
            }
        }
        try {
            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
            const maybeNewAnswer = yield call(examServerApi.selectAnswerVersion, questionId, questionText);
            if (maybeNewAnswer) {
                yield put(saveAnswer(maybeNewAnswer));
                if (examServerApi.logActivity) {
                    yield call(examServerApi.logActivity, `Restored answer version for question ${questionId}, ${questionText}`);
                }
            }
        }
        catch (error) {
            console.error('Restoring answer failed', error);
        }
    }
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export default function* root(examServerApi) {
    yield fork(answersSaga, examServerApi);
    yield fork(answerHistorySaga, examServerApi);
}
//# sourceMappingURL=sagas.js.map