import {useStorage} from "@vueuse/core";

const key = 'PaperStorage'
export const usePaperStorage = function (body) {
    const bodyStr = JSON.stringify(body)
    const paper = useStorage(key, bodyStr)
    paper.value = bodyStr
    return {paper}
}

export const usePaperResolver = function () {
    const paper = useStorage(key, null)
    const paperLocal = ref(JSON.parse(paper.value))
    const groupedQuestions = ref([])
    const resolvePaper = (function () {
        const results = {}
        paperLocal.value.questions.forEach(q => {
            if (!results[q.qtpye]) results[q.qtpye] = []
            results[q.qtpye].push(q)
        })
        groupedQuestions.value = Object.keys(results).map(g => ({
            title: g,
            list: results[g],
            num: results[g].length,
            score: results[g].reduce((acc, current) => acc + current.score, 0)
        }))
    })()

    const toCommitPaper = function () {
        const questions = []
        groupedQuestions.value.forEach(g => questions.push(...g.list))
        return {
            ...paperLocal.value,
            questions
        }
    }

    return {
        paperLocal, groupedQuestions, resolvePaper, toCommitPaper
    }
}