package com.tomhempel.rbarometer.questionnaire

import com.tomhempel.rbarometer.R
import com.tomhempel.rbarometer.network.TokenStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

open class QuestionnaireGeneric(private val questionnaireFileName: String) : QuestionnaireBase<Unit>() {

    override fun startQuestionnaire() {
        val (meta, questionsList) = loadQuestionnaireFromJson(questionnaireFileName)
        questionnaireMeta = meta
        questions = questionsList
        currentIndex = 0

        val clientCode = GlobalValues.LOADED_CLIENT_CODE?.trim().orEmpty()
            .ifEmpty { GlobalValues.LAST_CLIENT_CODE?.trim().orEmpty() }
        if (clientCode.isEmpty()) {
            showCurrentQuestion()
            return
        }

        CoroutineScope(Dispatchers.Main).launch {
            withContext(Dispatchers.IO) {
                SavedAnswerLoader.loadInto(
                    clientCode = clientCode,
                    questionnaireId = meta.id,
                    questions = questionsList,
                    answers = answers,
                )
            }
            answers["client_code"] = clientCode
            TokenStore.getUsername(context)?.let { answers["coach_code"] = it }
            showCurrentQuestion()
        }
    }

    override fun showCurrentQuestion() {
        val question = questions[currentIndex]
        val layoutResId = getLayoutResId(question.layout ?: "default_layout")
        if (layoutResId == 0) {
            showEmptyScreen()
            return
        }

        navigateTo(layoutResId) { layout ->
            layout.findViewById<android.widget.Button>(R.id.Qprev)?.setOnClickListener {
                goToPreviousQuestion()
            }
            val handler = createHandlerForQuestion(question)
            if (handler != null) {
                handler.bind(layout, question)
            } else {
                showEmptyScreen()
            }
        }
    }
}
