package com.sambath.kunkhmer.screen.login

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.sambath.kunkhmer.R
import com.sambath.kunkhmer.app.AdminActivity
import com.sambath.kunkhmer.app.App
import com.sambath.kunkhmer.app.MainActivity
import com.sambath.kunkhmer.app.ShareActivity
import com.sambath.kunkhmer.remote.User
import com.sambath.kunkhmer.screen.register.RegisterActivity
import com.sambath.kunkhmer.util.Const
import com.sambath.kunkhmer.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)*/
        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())
        }

        btn_signup.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
            finishAffinity()
        }
    }

    private fun render(state: LoginViewState) {
        if (state.isProgress) {
            tv_error.text = ""
        }
        if (state.isLoginSuccess) {
            if (state.userName == "kk001") {
                val intent = Intent(this, AdminActivity::class.java)
                startActivity(intent)
                finishAffinity()
            } else {
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finishAffinity()
            }
        }
        if (state.error != null) {
            tv_error.text = state.error
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}