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.TextView
import android.widget.Toast
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.fragment_kuesioner.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import ta1.cis.R
import ta1.cis.adapter.KuesionerAdapter
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.SharedPref
import ta1.cis.model.response.DataKuesioner
import ta1.cis.model.response.ResponseKuesioner

class  KuesionerFragment : Fragment() {
    private lateinit var sharedPref: SharedPref
    private lateinit var klikJudul: TextView

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

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        refreshlayoutkuesioner.setOnRefreshListener {
            fetchKuesioner()
        }
        fetchKuesioner()
    }

    private fun fetchKuesioner(){
        refreshlayoutkuesioner.isRefreshing = true

        RetrofitInstance.instanceRetrofit.getKuesioner().enqueue(object : Callback<ResponseKuesioner>{
            override fun onResponse(
                call: Call<ResponseKuesioner>,
                response: Response<ResponseKuesioner>
            ) {
                val kuesioner = response.body()
                refreshlayoutkuesioner.isRefreshing = false
                var mykuesioner = kuesioner?.data
                Log.d("Kuesioner",mykuesioner.toString())
                    showKuesioner(mykuesioner)
            }

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

        })
    }

    private fun showKuesioner(mykuesioner: List<DataKuesioner?>?){
        var adapterMyKuesioner = KuesionerAdapter(mykuesioner)

        var kuesionerAdapter = ConcatAdapter(adapterMyKuesioner)
        recyclerViewKuesioner.layoutManager = LinearLayoutManager(activity)
        recyclerViewKuesioner.adapter = kuesionerAdapter
    }


}