import { parentPort } from 'node:worker_threads'
import { Question, QuestionDb } from '../../types/basicTypes'
import { updateQuestionsInArray } from '../../utils/actions'

export type RmQuestionsTaskObject = {
    type: 'rmQuestions'
    data: {
        questionIndexesToRemove: number[][]
        subjIndex: number
        qdbIndex: number
        recievedQuestions: Question[]
    }
}

export const handleRmQuestions = async (
    qdbs: QuestionDb[],
    msg: RmQuestionsTaskObject,
    workerIndex: number,
    setQdbs: (newVal: QuestionDb[]) => void
): Promise<void> => {
    const { questionIndexesToRemove, subjIndex, qdbIndex, recievedQuestions } =
        msg.data

    const newQdbs = qdbs.map((qdb, i) => {
        if (i === qdbIndex) {
            return {
                ...qdb,
                data: qdb.data.map((subj, j) => {
                    if (j === subjIndex) {
                        return {
                            ...subj,
                            Questions: updateQuestionsInArray(
                                questionIndexesToRemove,
                                qdbs[qdbIndex].data[subjIndex].Questions,
                                recievedQuestions
                            ),
                        }
                    } else {
                        return subj
                    }
                }),
            }
        } else {
            return qdb
        }
    })
    setQdbs(newQdbs)

    parentPort.postMessage({
        msg: `From thread #${workerIndex}: rm question done`,
        workerIndex: workerIndex,
    })
}
