package com.sambath.klaklouk_main.screen.login

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

class LoginActivity : AppCompatActivity() {
    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.getUser(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())
        }
    }

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

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