package ta1.cis.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_edit_data_sekolah.*
import kotlinx.android.synthetic.main.d__asal_sekolah.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.awaitResponse
import ta1.cis.R
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.SharedPref
import ta1.cis.model.request.EditSekolah

class EditDataSekolahActivity : AppCompatActivity() {
    private lateinit var sharedPref: SharedPref
    private lateinit var btnEdit:Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_data_sekolah)
        setSupportActionBar(topAppBar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        sharedPref = SharedPref(this)
        val NoIjazah = intent.getStringExtra("No_Ijazah_SMA")
        etNoIjazahSMA.setText(NoIjazah)

        val NamaSMA = intent.getStringExtra("Nama_SMA")
        etAsalSekolah.setText(NamaSMA)

        saveEditSekolah.setOnClickListener {
            pb_editDataSekolah.visibility = View.VISIBLE
            var data = EditSekolah(
                etNoIjazahSMA.text.toString(),
                etAsalSekolah.text.toString()
            )
            Log.d("HalloButton",data.toString());
            editDataAsalSekolah(data)
        }
        topAppBar.setNavigationOnClickListener {
            onBackPressed()
        }
    }

    fun editDataAsalSekolah(data: EditSekolah){
        GlobalScope.launch(Dispatchers.IO) {
            val response = RetrofitInstance.instanceRetrofit.updateDataSekolah("Bearer ${sharedPref.getTokenBearer()}",data.noIjazah.toString(),data.namaSma).awaitResponse()
            if(response.isSuccessful){
                withContext(Dispatchers.Main){
                    Log.d("Hallo",response.body()?.data.toString());

                    pb_editDataSekolah.visibility = View.GONE
                    sharedPref.setStatusUpdate(2)
                    Toast.makeText(baseContext,"Data berhasil di update",Toast.LENGTH_SHORT).show()
                    onBackPressed()
                }
            }
        }
    }
}