package ta1.cis.fragment

import android.content.Context
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.LinearLayout
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.materi_fragment.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.awaitResponse
import ta1.cis.R
import ta1.cis.activity.MatakuliahActivity
import ta1.cis.adapter.MateriHeader
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.SharedPref
import ta1.cis.model.response.ResponseMateriKul

class MateriFragment() : Fragment() {

    private lateinit var matkul: MatakuliahActivity
    private lateinit var sharedPref: SharedPref
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.materi_fragment, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        matkul = activity as MatakuliahActivity
        sharedPref = SharedPref(activity as Context)
        setupRecycle()
    }

    private fun setupRecycle() {
        RetrofitInstance.instanceRetrofit.getMateriKuliah(matkul.getKuliahId(),"Bearer ${sharedPref.getTokenBearer()}")
            .enqueue(object : Callback<ResponseMateriKul>{
                override fun onResponse(
                    call: Call<ResponseMateriKul>,
                    response: Response<ResponseMateriKul>
                ) {
                    var data = response?.body()?.data
                    if(data != null){
                        rv_materi.layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
                        rv_materi.adapter = MateriHeader(context,data)
                    }else{
                        Toast.makeText(context,"Data Tidak ada",Toast.LENGTH_LONG).show()
                    }
                }

                override fun onFailure(call: Call<ResponseMateriKul>, t: Throwable) {
                    Toast.makeText(context,t.message.toString(),Toast.LENGTH_SHORT).show()
                }
            })
    }
}