package ta1.cis.fragment

import android.content.Context
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import fragment.PaketViewModel
import kotlinx.android.synthetic.main.paket2_fragment.*
import model.response.Paket
import model.response.ResponsePaket
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import ta1.cis.R
import ta1.cis.adapter.PaketAdapter
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.SharedPref

class PaketFragment : Fragment() {

    private lateinit var sharedPref: SharedPref

    companion object {
        fun newInstance() = PaketFragment()
    }

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

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        refreshlayout.setOnRefreshListener {
            fetchPaket()
        }
        fetchPaket()
    }


    private fun fetchPaket(){
        refreshlayout.isRefreshing = true

        RetrofitInstance.instanceRetrofit.getPaket("Bearer ${sharedPref.getTokenBearer()}").enqueue(object : Callback<ResponsePaket>{
            override fun onFailure(call: Call<ResponsePaket>, t: Throwable) {
                refreshlayout.isRefreshing = false
                Toast.makeText(activity, t.message, Toast.LENGTH_LONG).show()
            }
            override fun onResponse(
                call: Call<ResponsePaket>,
                response: Response<ResponsePaket>
            ) {
                val paket = response.body()
                refreshlayout.isRefreshing = false

                paket?.let {
                    var mylistpaket = it.data.myPaket
                    var otherlistpaket = it.data.otherPaket
                    showPaket(mylistpaket, otherlistpaket)
                }
            }

        })

    }
    private fun showPaket(mylistpaket: List<Paket>, otherlistpaket: List<Paket>){
        var adapterMyPaket = PaketAdapter(mylistpaket)
        var adapterOtherPaket = PaketAdapter(otherlistpaket)
        var paketAdapter = ConcatAdapter(adapterMyPaket, adapterOtherPaket)
        recyclerViewPaket.layoutManager = LinearLayoutManager(activity)
        recyclerViewPaket.adapter = paketAdapter
    }

}