package com.dano.test1.questionnaire

import android.view.Gravity
import android.view.View
import android.widget.AdapterView
import android.widget.Button
import android.widget.FrameLayout
import android.widget.Spinner
import com.dano.test1.R
import com.dano.test1.utils.ViewUtils

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

    override fun startQuestionnaire() {
        val (meta, questionsList) = loadQuestionnaireFromJson(questionnaireFileName)
        questionnaireMeta = meta
        questions = questionsList
        currentIndex = 0
        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<Button>(R.id.Qprev)?.setOnClickListener {
                goToPreviousQuestion()
            }

            val handler = createHandlerForQuestion(question)

            if (handler != null) {
                handler.bind(layout, question)
            } else {
                showEmptyScreen()
            }

            injectLanguageSpinner(layout)
        }
    }

    private fun injectLanguageSpinner(layout: View) {
        val container = layout as? FrameLayout ?: return

        val spinner = Spinner(context)
        val labels = AppLanguages.spinnerLabels(languageID)
        val selected = labels.getOrNull(AppLanguages.indexOf(languageID))
        ViewUtils.setupLanguagePickerSpinner(context, spinner, labels, selected)
        spinner.setSelection(AppLanguages.indexOf(languageID))

        val margin = ViewUtils.dp(context, 10)
        container.addView(
            spinner,
            FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT,
                Gravity.TOP or Gravity.END
            ).apply { setMargins(0, margin, margin, 0) }
        )

        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, v: View?, position: Int, id: Long) {
                val newLang = AppLanguages.ids[position]
                if (newLang == languageID) return
                languageID = newLang
                com.dano.test1.ui.AppLanguageStore.set(context, newLang)
                spinner.post { showCurrentQuestion() }
            }
            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
    }
}
