package com.example.courseworkkotlin

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.courseworkkotlin.databinding.ActivityTemperBinding

class Temper : AppCompatActivity() {
    private lateinit var binding: ActivityTemperBinding

    private var results = IntArray(4)
    private var questionId = 0
    private lateinit var questions: Array<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityTemperBinding.inflate(layoutInflater)
        setContentView(binding.root)

        questions = resources.getStringArray(R.array.Temper_Questions)

        binding.ButtonYes.setOnClickListener { processQuestion(1) }
        binding.ButtonNo.setOnClickListener { processQuestion(0) }

        binding.home.setOnClickListener { startActivity(Intent(this, HomeScreen::class.java)) }

        trackQuestionNumber()
        setQuestion()
    }

    private fun trackQuestionNumber() {
        binding.tracker.text = String.format("%s/%s", questionId + 1, questions.size)
    }

    private fun setQuestion() {
        binding.TemperQuestion.text = questions[questionId]
    }
    
    private fun processQuestion(amount: Int) {
        when (questionId) {
            in 0..19 -> results[0] += amount
            in 20..39 -> results[1] += amount
            in 40..59 -> results[2] += amount
            in 60..79 -> results[3] += amount
        }

        if (questionId < questions.size - 1) {
            questionId ++

            setQuestion()
            trackQuestionNumber()
        } else {
            val intent = Intent(this, TemperResult::class.java).apply { putExtra("answers", results) }
            startActivity(intent)
        }
    }
}