package com.tomhempel.rbarometer.questionnaire

import android.content.Context
import com.tomhempel.rbarometer.MainActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext

object QuestionnaireCompletionService {

    suspend fun completeAndFinish(
        context: Context,
        answers: Map<String, Any>,
        questionnaireId: String,
        languageId: String,
        questions: List<QuestionItem> = emptyList(),
        minLoadingMs: Long = 2000L,
        onCompleted: (() -> Unit)? = null,
    ) {
        val start = System.currentTimeMillis()
        QuestionnairePersistence.saveAnswers(context, answers, questionnaireId, languageId, questions)

        (answers["client_code"] as? String)?.let { code ->
            GlobalValues.LAST_CLIENT_CODE = code
            GlobalValues.LOADED_CLIENT_CODE = code
        }

        val elapsed = System.currentTimeMillis() - start
        if (elapsed < minLoadingMs) delay(minLoadingMs - elapsed)

        withContext(Dispatchers.Main) {
            onCompleted?.invoke() ?: (context as? MainActivity)?.finishQuestionnaire(wasCompleted = true)
        }
    }
}
