package com.dano.test1.ui

import android.os.Bundle
import android.widget.Button
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SwitchCompat
import androidx.appcompat.widget.Toolbar
import com.dano.test1.R

/**
 * Dev-only A/B settings. Entry: client code [_dev_settings_] on the opening screen Load action.
 * Not a security boundary (secret string is in the APK).
 */
class DevSettingsActivity : AppCompatActivity() {

    private lateinit var switchOverride: SwitchCompat
    private lateinit var radioGroup: RadioGroup

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

        val toolbar = findViewById<Toolbar>(R.id.devSettingsToolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        switchOverride = findViewById(R.id.switchAbOverride)
        radioGroup = findViewById(R.id.radioGroupVariant)

        applyPrefsToUi()

        switchOverride.setOnCheckedChangeListener { _, isChecked ->
            AbTestSettingsStore.setOverrideEnabled(this, isChecked)
            updateRadiosEnabled(isChecked)
        }

        radioGroup.setOnCheckedChangeListener { _, checkedId ->
            val variant = when (checkedId) {
                R.id.radioVariantA -> AbTestSettingsStore.VARIANT_A
                R.id.radioVariantB -> AbTestSettingsStore.VARIANT_B
                else -> AbTestSettingsStore.VARIANT_NONE
            }
            AbTestSettingsStore.setVariant(this, variant)
        }

        val databaseButton = findViewById<Button>(R.id.databaseButton)
        DatabaseButtonHandler(
            activity = this,
            databaseButton = databaseButton,
            onClose = { recreate() }
        ).setup()
    }

    private fun applyPrefsToUi() {
        val overrideOn = AbTestSettingsStore.isOverrideEnabled(this)
        switchOverride.isChecked = overrideOn
        updateRadiosEnabled(overrideOn)

        when (AbTestSettingsStore.getVariant(this)) {
            AbTestSettingsStore.VARIANT_A -> radioGroup.check(R.id.radioVariantA)
            AbTestSettingsStore.VARIANT_B -> radioGroup.check(R.id.radioVariantB)
            else -> radioGroup.check(R.id.radioVariantDefault)
        }
    }

    private fun updateRadiosEnabled(enabled: Boolean) {
        for (i in 0 until radioGroup.childCount) {
            (radioGroup.getChildAt(i) as? RadioButton)?.isEnabled = enabled
        }
        radioGroup.alpha = if (enabled) 1f else 0.5f
    }

    override fun onSupportNavigateUp(): Boolean {
        finish()
        return true
    }
}
