import { getData } from "@api/quizRelase";
import { parseQuizData } from "@model/api/getQuizData";
import { QuizSettings } from "@model/settingsData";
import useSWR from "swr";
import { useQuizId } from "../../contexts/QuizIdContext";
import { replaceSpacesToEmptyLines } from "../../pages/ViewPublicationPage/tools/replaceSpacesToEmptyLines";


export function useQuizData() {
    const quizId = useQuizId();
    const { data } = useSWR(["quizData", quizId], params => getQuizData(params[1]), {
        suspense: true,
    });

    return data;
}

async function getQuizData(quizId: string) {
    const response = await getData(quizId);
    const quizDataResponse = response.data;

    if (response.error) {
        throw new Error(response.error);
    }
    if (!quizDataResponse) {
        throw new Error("Quiz not found");
    }

    const quizSettings = replaceSpacesToEmptyLines(parseQuizData(quizDataResponse));

    const res = JSON.parse(JSON.stringify({ data: quizSettings }).replaceAll(/\\" \\"/g, '""').replaceAll(/" "/g, '""')).data as QuizSettings;
    res.recentlyCompleted = response.isRecentlyCompleted;
    return res;
} 
