package com.example.modifier.ui.login

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewModelScope
import com.example.modifier.Global
import com.example.modifier.R
import com.example.modifier.Utils
import com.example.modifier.databinding.ActivityLoginBinding
import com.example.modifier.model.ServerConfig
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class LoginActivity : AppCompatActivity() {
    private val loginViewModel: LoginViewModel by viewModels()
    private lateinit var binding: ActivityLoginBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login)
        binding.loginViewModel = loginViewModel
        binding.lifecycleOwner = this

        binding.etServer.setSimpleItems(Global.servers.toTypedArray())
        binding.btnLogin.setOnClickListener { v ->
            loginViewModel.serverConfig.value!!.url = binding.etServer.text.toString()
            loginViewModel.serverConfig.value!!.deviceLabel = binding.etDeviceLabel.text.toString()
            loginViewModel.serverConfig.value!!.username = binding.etUsername.text.toString()
            loginViewModel.serverConfig.value!!.password = binding.etPassword.text.toString()
            loginViewModel.viewModelScope.launch {
                loginViewModel.login()
            }
        }
        loginViewModel.serverConfig.postValue(ServerConfig())
        lifecycleScope.launch {
            // repeatOnLifecycle launches the block in a new coroutine every time the
            // lifecycle is in the STARTED state (or above) and cancels it when it's STOPPED.
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                // Trigger the flow and start listening for values.
                // Note that this happens when lifecycle is STARTED and stops
                // collecting when the lifecycle is STOPPED
                loginViewModel.uiState.collect { uiState ->
                    // New value received
                    when (uiState) {
                        is LoginUiState.Normal -> {}
                        is LoginUiState.Loading -> Utils.makeLoadingButton(
                            this@LoginActivity,
                            binding.btnLogin
                        )

                        is LoginUiState.Success -> {}
                        is LoginUiState.Error -> {}
                        is LoginUiState.NoRootAccess -> {}
                    }
                }
            }
        }
    }
}