package com.proyek.akhir.kodel.ui.user.produk

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.proyek.akhir.kodel.R
import com.proyek.akhir.kodel.data.response.ProdukItem
import kotlinx.android.synthetic.main.fragment_produk.*
import kotlinx.android.synthetic.main.fragment_produk.view.*
import kotlinx.android.synthetic.main.fragment_produk.view.refreshProductUser

class ProdukFragment : Fragment() {
    private val listProduk: MutableList<ProdukItem> = mutableListOf()
    private lateinit var produkAdapter: ProdukAdapter
    private lateinit var produkViewModel: ProdukViewModel
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fragment_produk, container, false)
        root.rvProduk.setHasFixedSize(true)

        root.refreshProductUser.setOnRefreshListener {
            root.refreshProductUser.isRefreshing = true
            callProduk()
        }

        root.progressbarProductUser.visibility = View.VISIBLE

        callProduk()

        root.rvProduk.layoutManager =
            LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        produkAdapter = ProdukAdapter(listProduk)
        root.rvProduk.adapter = produkAdapter

        return root
    }
    private fun callProduk() {
        produkViewModel = ViewModelProvider(this).get(ProdukViewModel::class.java)
        produkViewModel.setDataProduk().observe(viewLifecycleOwner, Observer { produk ->
            if (produk != null) {
                listProduk.clear()
                for (i in 0 until produk.size) {
                    listProduk.add(produk[i])
                }

                refreshProductUser.isRefreshing = false
                progressbarProductUser.visibility = View.GONE
                rvProduk.visibility = View.VISIBLE
//                Toast.makeText(context, produk[0].namaProduk, Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(context, "Jaringan Lemah", Toast.LENGTH_SHORT).show()
                progressbarProductUser.visibility = View.GONE
                rvProduk.visibility = View.GONE
            }
        })
    }
}
