package com.base.pdfreaderallpdfreader.ui.main.recent

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.base.pdfreaderallpdfreader.databinding.FragmentRecentBinding
import com.base.pdfreaderallpdfreader.ui.main.DocumentAdapter
import com.base.pdfreaderallpdfreader.utils.LogEx
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.random.Random


class RecentFragment() : Fragment() {

    private val TAG = "RecentFragment"

    private var _binding: FragmentRecentBinding? = null

    private val binding get() = _binding!!
    private lateinit var recentViewModel: RecentViewModel
    private var adapter: DocumentAdapter? = null

    var i = Random(100).nextInt()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        LogEx.logDebug(TAG, "onCreate $i")
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        recentViewModel = ViewModelProvider(this)[RecentViewModel::class.java]
        _binding = FragmentRecentBinding.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() {
//        if (!recentNeedRefresh) return
//        recentNeedRefresh = false
        binding.swipeRefreshLayout.isRefreshing = true

        lifecycleScope.launch(Dispatchers.IO) {

            val recentList = recentViewModel.getRecentDocument(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
            }
        }
    }

    companion object {
        var recentNeedRefresh = true
    }


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
        LogEx.logDebug(TAG, "onDestroyView $i")
    }

    override fun onDestroy() {
        super.onDestroy()
        LogEx.logDebug(TAG, "onDestroy $i")
    }
}