package ta1.cis.activity

import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.Connectivity
import ta1.cis.helper.CustomDialog
import ta1.cis.helper.SharedPref
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import ta1.cis.model.request.LoginRequest
import ta1.cis.model.response.ResponseModel
import retrofit2.Call
import retrofit2.Response
import ta1.cis.activity.HomeActivity
import ta1.cis.R
import ta1.cis.service.NotificationService
import kotlin.coroutines.CoroutineContext


class LoginActivity : AppCompatActivity() {
    lateinit var sharedPref: SharedPref
    lateinit var progressDialog: CustomDialog
    override fun onCreate(savedInstanceState: Bundle?){
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        sharedPref = SharedPref(this)
        if(sharedPref.getTokenBearer() != ""){
            Log.d("LoginAcc1",sharedPref.getUserId().toString())
            val intent = Intent(this@LoginActivity, HomeActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
            startService(Intent(this,NotificationService::class.java))
            startActivity(intent)
            finish()
        }
        btn_login.setOnClickListener {
            login()
        }

    }

    fun login(){
        if (edt_username.text!!.isEmpty()){
            edt_username.error = "Kolom Username tidak boleh kosong"
            edt_username.requestFocus()
        } else if (edt_password.text!!.isEmpty()){
            edt_password.error = "Kolom Password tidak boleh kosong"
            edt_password.requestFocus()
        }
        pb_login.visibility = View.VISIBLE
        val requestLogin = LoginRequest(
            edt_username.text.toString(),
            edt_password.text.toString()
        )
        if(Connectivity.isNetworkAvailable(this as Context)) {
            RetrofitInstance.instanceRetrofit.login(requestLogin)
                .enqueue(object : retrofit2.Callback<ResponseModel> {
                    override fun onFailure(call: Call<ResponseModel>, t: Throwable) {
                        pb_login.visibility = View.GONE
                        Toast.makeText(
                            this@LoginActivity,
                            "Error " + t.message,
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                    override fun onResponse(
                        call: Call<ResponseModel>,
                        response: Response<ResponseModel>
                    ) {
                        pb_login.visibility = View.GONE
                        if (response.isSuccessful) {
                            val respon = response.body()!!
                            Log.d("Status", respon.status.toString());
                            sharedPref.setStatusLogin(true)
                            sharedPref.setToken(respon.data?.token)
                            sharedPref.setDimId(respon.data?.user?.dimId)
                            sharedPref.setUserId(respon.data?.user?.userId)
                            sharedPref.setUsername(edt_username.text.toString())
                            Log.d("Ini Token tersimpan",sharedPref.getTokenBearer())
                            val intent = Intent(this@LoginActivity, HomeActivity::class.java)
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
                            startService(Intent(this@LoginActivity,NotificationService::class.java))
                            startActivity(intent)
                            finish()
                            Toast.makeText(
                                this@LoginActivity,
                                "Selamat datang ",
                                Toast.LENGTH_SHORT
                            ).show()
                        }else{
                            Toast.makeText(this@LoginActivity,"Password/Username anda salah",Toast.LENGTH_LONG).show()
                        }
                    }
                })
        }
    }
}
