package com.example.maposition

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText

class SettingsActivity : AppCompatActivity() {

    private lateinit var groupsList: LinearLayout

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

        groupsList = findViewById(R.id.groupsList)

        val nameInput = findViewById<TextInputEditText>(R.id.nameInput)
        nameInput.setText(Prefs.getName(this))
        nameInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
            override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
            override fun afterTextChanged(s: Editable?) {
                Prefs.setName(this@SettingsActivity, s?.toString() ?: "")
            }
        })

        findViewById<ImageButton>(R.id.backButton).setOnClickListener { finish() }
        findViewById<MaterialButton>(R.id.addGroupButton).setOnClickListener {
            startActivity(Intent(this, EditGroupActivity::class.java))
        }
    }

    override fun onResume() {
        super.onResume()
        renderGroups()
    }

    private fun renderGroups() {
        groupsList.removeAllViews()
        val groups = Prefs.getGroups(this)

        if (groups.isEmpty()) {
            val empty = TextView(this).apply {
                text = getString(R.string.no_groups)
                setPadding(8, 24, 8, 24)
            }
            groupsList.addView(empty)
            return
        }

        val activeName = Prefs.getActiveGroup(this)?.name
        groups.forEach { g ->
            val item = layoutInflater.inflate(R.layout.item_group, groupsList, false)
            val title = if (g.name == activeName) {
                getString(R.string.group_active_suffix, g.name)
            } else {
                g.name
            }
            item.findViewById<TextView>(R.id.groupName).text = title
            item.findViewById<TextView>(R.id.groupPhones).text = g.displayList()
            item.setOnClickListener {
                startActivity(
                    Intent(this, EditGroupActivity::class.java)
                        .putExtra(EditGroupActivity.EXTRA_GROUP, g.name)
                )
            }
            groupsList.addView(item)
        }
    }
}
