package com.dano.test1.questionnaire.handlers

import android.view.View
import android.widget.*
import com.dano.test1.LanguageManager
import com.dano.test1.questionnaire.QuestionHandler
import com.dano.test1.questionnaire.QuestionItem
import com.dano.test1.R

/*
Zweck:
- Steuert die Seite „Client hat nicht unterschrieben“ im Fragebogenfluss.
- Speichert den eingegebenen Coach-Code in das Answers-Map unter question.id (saveAnswer), damit der nachfolgende Prozess darauf zugreifen kann.
*/

class HandlerClientNotSigned(
    private val answers: MutableMap<String, Any>,
    private val languageID: String,
    private val goToNextQuestion: () -> Unit,
    private val goToPreviousQuestion: () -> Unit,
    private val showToast: (String) -> Unit
) : QuestionHandler {

    private lateinit var layout: View
    private lateinit var question: QuestionItem.ClientNotSigned

    private lateinit var textView1: TextView
    private lateinit var textView2: TextView
    private lateinit var questionTextView: TextView
    private lateinit var coachCodeField: EditText

    override fun bind(layout: View, question: QuestionItem) {
        if (question !is QuestionItem.ClientNotSigned) return

        this.layout = layout
        this.question = question


        initViews()

        textView1.text = question.textKey1?.let { LanguageManager.getText(languageID, it) } ?: ""
        textView2.text = question.textKey2?.let { LanguageManager.getText(languageID, it) } ?: ""
        questionTextView.text = question.question?.let { LanguageManager.getText(languageID, it) } ?: ""

        coachCodeField.setText(answers[question.id] as? String ?: "")

        layout.findViewById<Button>(R.id.Qnext).setOnClickListener {
            onNextClicked()
        }

        layout.findViewById<Button>(R.id.Qprev).setOnClickListener {
            goToPreviousQuestion()
        }
    }

    private fun initViews() {
        textView1 = layout.findViewById(R.id.textView1)
        textView2 = layout.findViewById(R.id.textView2)
        questionTextView = layout.findViewById(R.id.question)
        coachCodeField = layout.findViewById(R.id.coach_code)
    }

    private fun onNextClicked() {
        if (validate()) {
            saveAnswer()
            goToNextQuestion()
        } else {
            val message = LanguageManager.getText(languageID, "enter_coach_code")
            showToast(message)
        }
    }

    override fun validate(): Boolean {
        val coachCode = coachCodeField.text
        return coachCode.isNotBlank()
    }

    override fun saveAnswer() {
        answers[question.id] = coachCodeField.text.toString()
    }
}
