import { FillBlanksExercise, FillBlanksMCOption } from "@/interfaces/exam";
import ExerciseItem from "./types";
import ExerciseLabel from "../../Shared/ExerciseLabel";
import FillBlanksLetters from "../../Exercises/Blanks/Letters";
import FillBlanksMC from "../../Exercises/Blanks/MultipleChoice";

interface LetterWord {
    letter: string;
    word: string;
}

function isLetterWordArray(words: (string | LetterWord | FillBlanksMCOption)[]): words is LetterWord[] {
    return words.length > 0 &&
        words.every(item =>
            typeof item === 'object' &&
            'letter' in item &&
            'word' in item &&
            !('options' in item)
        );
}

function isFillBlanksMCOptionArray(words: (string | LetterWord | FillBlanksMCOption)[]): words is FillBlanksMCOption[] {
    return words.length > 0 &&
        words.every(item =>
            typeof item === 'object' &&
            'id' in item &&
            'options' in item &&
            typeof (item as FillBlanksMCOption).options === 'object' &&
            'A' in (item as FillBlanksMCOption).options &&
            'B' in (item as FillBlanksMCOption).options &&
            'C' in (item as FillBlanksMCOption).options &&
            'D' in (item as FillBlanksMCOption).options
        );
}


const fillBlanks = (exercise: FillBlanksExercise, index: number, sectionId: number): ExerciseItem => {
    const firstWordId = exercise.solutions[0].id;
    const lastWordId = exercise.solutions[exercise.solutions.length - 1].id;


    if (isLetterWordArray(exercise.words)) {
        return {
            id: index.toString(),
            sectionId,
            label: (
                <ExerciseLabel
                    type='Fill Blanks Question'
                    firstId={firstWordId}
                    lastId={lastWordId}
                    prompt={exercise.prompt}
                />
            ),
            content: <FillBlanksLetters exercise={exercise} sectionId={sectionId} />
        };
    }

    if (isFillBlanksMCOptionArray(exercise.words)) {
        return {
            id: index.toString(),
            sectionId,
            label: (
                <ExerciseLabel
                    type='Fill Blanks: MC Question'
                    firstId={firstWordId}
                    lastId={lastWordId}
                    prompt={exercise.prompt}
                />
            ),
            content: <FillBlanksMC exercise={exercise} sectionId={sectionId} />
        };
    }

    // Don't know where the fillBlanks with words as string fits
    throw new Error(`Unsupported Exercise`);
}

export default fillBlanks;
