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.SearchView
import android.widget.Toast
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.fragment_pengumuman.*
import kotlinx.android.synthetic.main.paket2_fragment.*
import model.response.Pengumuman
import model.response.ResponsePengumuman
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import ta1.cis.R
import ta1.cis.adapter.PengumumanAdapter
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.SharedPref

class PengumumanFragment : Fragment() {

    private lateinit var sharedPref: SharedPref

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


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        refreshlayoutpengumuman.setOnRefreshListener {
            fetchPengumuman()
        }
        fetchPengumuman()
    }

    private fun fetchPengumuman(){
        refreshlayoutpengumuman.isRefreshing = true

        RetrofitInstance.instanceRetrofit.getPengumuman("Bearer ${sharedPref.getTokenBearer()}").enqueue(object : Callback<ResponsePengumuman>{
            override fun onResponse(
                call: Call<ResponsePengumuman>,
                response: Response<ResponsePengumuman>
            ) {
                val pengumuman = response.body()
                refreshlayoutpengumuman.isRefreshing = false
                Log.d("Pengumuman",pengumuman.toString())
                pengumuman?.let {
                    var mypengumuman = it.data

                    showPengumuman(mypengumuman)
                }
            }

            override fun onFailure(call: Call<ResponsePengumuman>, t: Throwable) {
                refreshlayoutpengumuman.isRefreshing = false
                Toast.makeText(activity, t.message, Toast.LENGTH_LONG).show()
            }

        })
    }

    private fun showPengumuman(mypengumuman: List<Pengumuman>){
        var adapterMyPengumuman = PengumumanAdapter(mypengumuman)

        var pengumumanAdapter = ConcatAdapter(adapterMyPengumuman)
        recyclerViewPengumuman.layoutManager = LinearLayoutManager(activity)
        recyclerViewPengumuman.adapter = adapterMyPengumuman

    }

}