package com.example.courseworkkotlin

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.example.courseworkkotlin.databinding.ActivityMbtiBinding

class MBTI : AppCompatActivity() {
    private lateinit var binding: ActivityMbtiBinding

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

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

        questions = resources.getStringArray(R.array.MBTI_Questions)
        answers = resources.getStringArray(R.array.MBTI_Answers)

        binding.ButtonA.setOnClickListener { processQuestion(binding.ButtonA) }
        binding.ButtonB.setOnClickListener { processQuestion(binding.ButtonB) }

        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.MBTIQuestion.text = questions[questionId]
        binding.MBTIAnswer.text = answers[questionId]
    }
    
    private fun processQuestion(buttonClicked: Button) {
        when (buttonClicked) {
            binding.ButtonA -> when (questionId) {
                0 -> results[0] = 'E'
                1 -> results[1] = 'S'
                2 -> results[2] = 'T'
                3 -> results[3] = 'J'
            }
            binding.ButtonB -> when (questionId) {
                0 -> results[0] = 'I'
                1 -> results[1] = 'N'
                2 -> results[2] = 'F'
                3 -> results[3] = 'P'
            }
        }

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

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