package com.khmer9.lotto.screen.login

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.khmer9.lotto.R
import com.khmer9.lotto.app.App
import com.khmer9.lotto.app.ShareActivity
import com.khmer9.lotto.remote.User
import com.khmer9.lotto.util.Const
import com.khmer9.lotto.util.ModelPreferencesManager
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : AppCompatActivity() {
    //private val loginViewModel = App.injectLoginViewModel()
    private lateinit var loginViewModel: LoginViewModel
    private var user: User?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        loginViewModel = LoginViewModel(App.injectApiService(), App.injectPrefHelper())

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_login)
        user = ModelPreferencesManager.get<User>(Const.USER_KEY)
        if (user != null) et_username.setText(user?.userName)

        //et_username.setText("AAVVAAAG002")
        //et_username.setText("AAVVAAAH007")
        //et_password.setText("1234567")

        loginViewModel.state.observe(this, Observer(this::render))


        btn_login.setOnClickListener {
            til_username.isErrorEnabled = false
            til_username.error = null
            til_password.isErrorEnabled = false
            til_password.error= null
            val username = et_username.text
            val password = et_password.text
            if (username.isNullOrEmpty()){
                til_username.error = getString(R.string.err_not_empty)
                til_username.requestFocus()
                return@setOnClickListener
            }
            if (password.isNullOrEmpty()){
                til_password.error = getString(R.string.err_not_empty)
                til_password.requestFocus()
                return@setOnClickListener
            }
            loginViewModel.login(username.toString(),password.toString())

        }

    }
    private fun render(state: LoginViewState) {

        if (state.isProgress){
            //Toast.makeText(this@LoginActivity, "Loading", Toast.LENGTH_LONG).show()
            tv_error.text = ""

        }
        if (state.isLoginSuccess){
            //Toast.makeText(this@LoginActivity, "ចូលប្រព័ន្ធជោគជ័យ", Toast.LENGTH_LONG).show()
            val intent = Intent(this, ShareActivity::class.java)
            startActivity(intent)
            finishAffinity()

        }
        if (state.error != null){
            //Toast.makeText(this@LoginActivity, "Error", Toast.LENGTH_LONG).show()
            tv_error.text = state.error

        }

    }

    override fun onDestroy() {
       // loginViewModel.state.removeObservers(this)
        super.onDestroy()
        //Toast.makeText(this@LoginActivity, "On Destroy Login", Toast.LENGTH_LONG).show()

    }
}