package ta1.cis.fragment.tabitem

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
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 okhttp3.Dispatcher
import retrofit2.*
import ta1.cis.R
import ta1.cis.activity.EditDataSekolahActivity
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.SharedPref
import ta1.cis.model.response.ResponseDataSekolah


class D_AsalSekolahFragment : Fragment() {

    private lateinit var sharedPref: SharedPref


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        sharedPref = SharedPref(activity as Context)
        fetchDataSekolah()
        return inflater.inflate(R.layout.d__asal_sekolah, container, false)
    }

    override fun onStart() {
        super.onStart()
        fetchDataSekolah()
    }
    private fun fetchDataSekolah(){
        GlobalScope.launch(Dispatchers.IO){
            val response = RetrofitInstance.instanceRetrofit.getDataSekolah("Bearer ${sharedPref.getTokenBearer()}").awaitResponse()
            if (response.isSuccessful){
                val data = response.body()!!

                withContext(Dispatchers.Main){
                    progressBar.visibility = View.GONE
                    data.data.forEach {
                        noijazah.text = it.noIjazah
                        namaSMA.text = it.namaSekolah
                        alamatSMA.text = it.alamatSekolah
                        kbptenSMA.text = it.kabupatenSma
                        teleponSMA.text = it.telepon
                        kdpos_SMA.text = it.kodePos
                    }
                }
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        btneditsekolah.setOnClickListener {
            var intent = Intent(activity, EditDataSekolahActivity::class.java)

            intent.putExtra("No_Ijazah_SMA", noijazah.text)

            intent.putExtra("Nama_SMA", namaSMA.text)
            startActivity(intent)
        }
        super.onViewCreated(view, savedInstanceState)
    }

}