package com.base.pdfreaderallpdfreader.ui.main.bookmark

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.base.pdfreaderallpdfreader.databinding.FragmentBookmarkBinding
import com.base.pdfreaderallpdfreader.ui.main.DocumentAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class BookmarkFragment : Fragment() {

    private var _binding: FragmentBookmarkBinding? = null

    // onDestroyView.
    private val binding get() = _binding!!
    private lateinit var bookmarkViewModel: BookmarkViewModel
    private var adapter: DocumentAdapter? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        bookmarkViewModel = ViewModelProvider(this)[BookmarkViewModel::class.java]

        _binding = FragmentBookmarkBinding.inflate(inflater, container, false)
        val root: View = binding.root

        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        adapter = DocumentAdapter()
        binding.rv.adapter = adapter
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

    private fun initData() {
        binding.swipeRefreshLayout.isRefreshing = true

        lifecycleScope.launch(Dispatchers.IO) {

            val recentList = bookmarkViewModel.getBookmarkDocument(requireContext())
            launch(Dispatchers.Main) {
                if (recentList.isEmpty()) {
                    binding.llEmpty.visibility = View.VISIBLE
                    adapter?.submitList(listOf())
                } else {
                    binding.llEmpty.visibility = View.GONE
                    adapter?.submitList(recentList)
                }
                binding.swipeRefreshLayout.isRefreshing = false
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}