package com.sambath.kunkhmer.screen.event

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.sambath.kunkhmer.R
import com.sambath.kunkhmer.adapter.EventAdapter
import com.sambath.kunkhmer.adapter.EventCardItem
import com.sambath.kunkhmer.app.App
import kotlinx.android.synthetic.main.fragment_event.view.recyclerViewEvent

class EventFragment : Fragment() {
    private var _root: View? = null
    private val binding get() = _root!!
    private lateinit var eventViewModel: EventViewModel
    private lateinit var eventAdapter: EventAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _root = inflater.inflate(R.layout.fragment_event, container, false)

        eventViewModel = EventViewModel(App.injectApiService(), App.injectPrefHelper())
        eventViewModel.getEvents()
        eventViewModel.state.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            render(it)
        })

        setEvent()

        return binding
    }

    private fun render(state: EventViewModel.EventViewState) {
        if (state.isProgress) {
        }
        if (state.isLoginSuccess) {
            if(state.eventsData != null) {
                eventAdapter.cardList = state.eventsData
                eventAdapter.notifyDataSetChanged()
            }
        }
        if (state.error != null) {
        }
    }

    private fun setEvent() {
        val recyclerView = binding.recyclerViewEvent
        eventAdapter = EventAdapter(mutableListOf())

        recyclerView.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        recyclerView.adapter = eventAdapter
    }
}