import { Action } from "@/stores/examEditor/reducers";
import { ExamPart, Generating } from "@/stores/examEditor/types";
import { createSpeakingExercise } from "./speaking";
import { writingTask } from "@/stores/examEditor/sections";
import { WritingExercise } from "@/interfaces/exam";

const getResults = (results: any[], type: 'writing' | 'speaking') => {
    return results.map((res) => {
        if (type === 'writing') {
            return {
                ...writingTask(res.generating === "writing_letter" ? 1 : 2),
                prompt: res.result[0].prompt,
                variant: res.generating === "writing_letter" ? "letter" : "essay"
              } as WritingExercise;
        }
        return createSpeakingExercise(res);
    });
};

const updates = (
    results: any[],
    sectionState: ExamPart,
    sectionId: number,
    currentModule: string,
    levelGenerating: any[],
    levelGenResults: any[],
    type: 'writing' | 'speaking'
): Action[] => {
    return [
        {
            type: "UPDATE_SECTION_STATE",
            payload: {
                sectionId,
                module: "level",
                update: {
                    exercises: [
                        ...(sectionState as ExamPart).exercises,
                        ...getResults(results, type)
                    ]
                }
            }
        },
        {
            type: "UPDATE_SECTION_SINGLE_FIELD",
            payload: {
                sectionId,
                module: currentModule,
                field: "levelGenerating",
                value: levelGenerating?.filter(g =>
                    !results.flatMap(res => res.generating as Generating).includes(g)
                )
            }
        },
        {
            type: "UPDATE_SECTION_SINGLE_FIELD",
            payload: {
                sectionId,
                module: currentModule,
                field: "levelGenResults",
                value: levelGenResults.filter(res =>
                    !results.flatMap(res => res.generating as Generating).includes(res.generating)
                )
            }
        }
    ] as Action[];
};