@file:Suppress("HardCodedStringLiteral")

package eu.gaudian.translator.model.repository

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import eu.gaudian.translator.model.Exercise
import eu.gaudian.translator.model.Question
import eu.gaudian.translator.utils.Log
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.firstOrNull

private const val TAG = "ExerciseRepository"

class ExerciseRepository {

    constructor(context: Context) {
        this.dataStore = context.dataStore
    }

    private val dataStore: DataStore<Preferences>


    fun getAllExercisesFlow(): Flow<List<Exercise>> {
        return dataStore.loadObjectList(DataStoreKeys.EXERCISES_KEY)
    }

    private suspend fun getAllExercises(): List<Exercise> {
        return getAllExercisesFlow().firstOrNull() ?: emptyList()
    }

    suspend fun saveExercise(exercise: Exercise) {
        try {
            val currentExercises = getAllExercises().toMutableList()
            val existingIndex = currentExercises.indexOfFirst { it.id == exercise.id }

            if (existingIndex != -1) {
                currentExercises[existingIndex] = exercise
            } else {
                currentExercises.add(exercise)
            }
            dataStore.saveObjectList(DataStoreKeys.EXERCISES_KEY, currentExercises)
        } catch (e: Exception) {
            Log.e(TAG, "Failed to save exercise", e)
        }
    }

    suspend fun deleteExercise(exerciseId: String) {
        try {
            val currentExercises = getAllExercises().toMutableList()
            if (currentExercises.removeAll { it.id == exerciseId }) {
                dataStore.saveObjectList(DataStoreKeys.EXERCISES_KEY, currentExercises)
                Log.d(TAG, "Successfully deleted exercise with ID: $exerciseId")
            }
        } catch (e: Exception) {
            Log.e(TAG, "Failed to delete exercise with ID: $exerciseId", e)
        }
    }



    fun getAllQuestionsFlow(): Flow<List<Question>> {
        return dataStore.loadObjectList(DataStoreKeys.QUESTIONS_KEY)
    }

    private suspend fun getAllQuestions(): List<Question> {
        return getAllQuestionsFlow().firstOrNull() ?: emptyList()
    }

    /**
     * Saves a list of questions to the DataStore, replacing any existing ones with the same ID.
     */
    private suspend fun saveQuestions(questions: List<Question>) {
        try {
            val currentQuestions = getAllQuestions().toMutableList()
            questions.forEach { newQuestion ->
                val index = currentQuestions.indexOfFirst { it.id == newQuestion.id }
                if (index != -1) {
                    currentQuestions[index] = newQuestion
                } else {
                    currentQuestions.add(newQuestion)
                }
            }
            dataStore.saveObjectList(DataStoreKeys.QUESTIONS_KEY, currentQuestions)
        } catch (e: Exception) {
            Log.e(TAG, "Failed to save questions", e)
        }
    }

    suspend fun saveNewExerciseWithQuestions(exercise: Exercise, questions: List<Question>) {
        saveQuestions(questions)
        saveExercise(exercise)
        Log.d(TAG, "Successfully saved new exercise '${exercise.title}' with ${questions.size} questions.")
    }
}