package com.example.lexilearn.data.repository

import com.example.lexilearn.data.model.AnswerType
import com.example.lexilearn.data.model.MaterialDataModel
import com.example.lexilearn.data.model.QuestionType
import com.example.lexilearn.data.model.QuizAnswer
import com.example.lexilearn.data.model.QuizQuestion
import kotlin.random.Random


class QuizRepository {

    /**
     * Fungsi ini akan membuat soal dengan mode soal & jawaban yang DITENTUKAN oleh parameter.
     */
    fun generateQuestion(
        material: MaterialDataModel,
        questionMode: Int,
        answerMode: Int
    ): QuizQuestion {
        val questionType = when (questionMode) {
            1 -> listOf(QuestionType.TEXT, QuestionType.IMAGE).random()  // Text atau Image
            2 -> QuestionType.AUDIO  // Hanya Audio
            else -> QuestionType.TEXT  // Default ke Text
        }

        val question = when (questionType) {
            QuestionType.TEXT -> listOf(material.idName, material.idDescription).random()
            QuestionType.IMAGE -> material.image
            QuestionType.AUDIO -> material.enName
        } ?: "Soal tidak tersedia"

        val answerType = when (answerMode) {
            1 -> AnswerType.FULL_WORD
            2 -> AnswerType.SHUFFLED_LETTERS
            else -> AnswerType.FULL_WORD
        }

        return QuizQuestion(
            questionType = questionType,
            question = question,
            correctAnswer = QuizAnswer(
                answerType = answerType,
                correctWord = material.enName
            )
        )
    }

    /**
     * Fungsi ini akan membuat soal dengan mode soal & jawaban yang DIPILIH SECARA ACAK.
     */
    fun generateRandomQuestion(material: MaterialDataModel): QuizQuestion {
        val randomQuestionMode = Random.nextInt(1, 3) // Acak antara 1 (Text/Image) atau 2 (Audio)
        val randomAnswerMode =
            Random.nextInt(1, 3)   // Acak antara 1 (FULL_WORD) atau 2 (SHUFFLED_LETTERS)

        return generateQuestion(material, randomQuestionMode, randomAnswerMode)
    }

    fun getRandomMaterials(
        nData: Int,
        materials: List<MaterialDataModel>,
        callback: (List<MaterialDataModel>) -> Unit
    ) {
        if (materials.isNotEmpty()) {
            val randomMaterials = materials.shuffled().take(nData)
            callback(randomMaterials)
        } else {
            callback(emptyList())
        }
    }

}