package com.b2lmobitech.fieldcloudhrms

import android.content.Context
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.recyclerview.widget.LinearLayoutManager
import com.b2lmobitech.fieldcloudhrms.databinding.FragmentLeaveBalanceBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class LeaveBalanceFragment : Fragment() {

    private lateinit var binding: FragmentLeaveBalanceBinding
    private lateinit var adapter: LeaveBalanceAdapter
    private val list = ArrayList<LeaveBalanceModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {

        binding = FragmentLeaveBalanceBinding.inflate(inflater, container, false)

        binding.recyclerLeaveBalance.layoutManager =
            LinearLayoutManager(requireContext())

        adapter = LeaveBalanceAdapter(list)
        binding.recyclerLeaveBalance.adapter = adapter

        loadLeaveBalance()

        return binding.root
    }

    private fun loadLeaveBalance() {

        val pref = requireContext().getSharedPreferences("login_pref", Context.MODE_PRIVATE)
        val peopleId = pref.getString("user_id", "") ?: return

        RetrofitClient.instance.getLeaveBalance(peopleId)
            .enqueue(object : Callback<LeaveBalanceResponse> {

                override fun onResponse(
                    call: Call<LeaveBalanceResponse>,
                    response: Response<LeaveBalanceResponse>
                ) {
                    val res = response.body()
                    if (res != null && res.success) {
                        list.clear()
                        list.addAll(res.data)
                        adapter.notifyDataSetChanged()
                    }
                }

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