package fr.iut.pm.quiz

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


private const val EXTRA_ANSWER_IS_TRUE = "fr.iut.pm.quiz.answer_is_true"
private const val EXTRA_ANSWER_SHOWN = "fr.iut.pm.quiz.answer_shown"

class CheatActivity : AppCompatActivity() {
    private var answerIsTrue = false
    private var answerShown = false

    private lateinit var textViewAnswer : TextView

    companion object {
        fun newIntent(context: Context, answerIsTrue: Boolean) =
                Intent(context, CheatActivity::class.java).apply {
                    putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue)
                }

        fun wasAnswerShown(result: Intent) = result.getBooleanExtra(EXTRA_ANSWER_SHOWN, false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_cheat)

        textViewAnswer = findViewById(R.id.textView_answer)

        answerIsTrue = intent.getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false)
        savedInstanceState?.let {
            answerShown = it.getBoolean(EXTRA_ANSWER_SHOWN)
            if (answerShown) showAnswer()
        }
        findViewById<Button>(R.id.button_show_answer).setOnClickListener { showAnswer() }
    }

    private fun showAnswer() {
        answerShown = true
        textViewAnswer.setText(if (answerIsTrue) R.string.text_button_true else R.string.text_button_false)
        setHasCheated()
    }

    private fun setHasCheated() {
        val data = Intent().apply { putExtra(EXTRA_ANSWER_SHOWN, true) }
        setResult(Activity.RESULT_OK, data)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putBoolean(EXTRA_ANSWER_SHOWN, answerShown)
    }
}
