package ta1.cis.fragment

import android.app.Activity
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.fragment_jadwal.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.await
import retrofit2.awaitResponse
import ta1.cis.R
import ta1.cis.adapter.JadwalHeaderAdapter
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.SharedPref

class JadwalFragment : Fragment() {

    private lateinit var sharedPref: SharedPref

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        sharedPref = SharedPref(context as Activity)
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_jadwal, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        pb_jadwal.visibility = View.VISIBLE
        callApiJadwal()
    }

    fun callApiJadwal(){
        GlobalScope.launch(Dispatchers.IO) {
            val response = RetrofitInstance.instanceRetrofit.getAllJadwal("Bearer ${sharedPref.getTokenBearer()}").awaitResponse()
            if(response.isSuccessful){
                withContext(Dispatchers.Main){
                    val data = response.body()?.data
                    if(data != null){
                        pb_jadwal.visibility = View.GONE
                        recyclerViewJadwal.layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
                        recyclerViewJadwal.adapter = JadwalHeaderAdapter(context,data)
                    }else{
                        pb_jadwal.visibility = View.GONE
                    }
                }
            }
        }
    }

}