package com.keyboard.craft.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import com.keyboard.craft.CraftApp
import com.keyboard.craft.adapter.KeyDetailsDataAdapter
import com.keyboard.craft.bean.ItemDataBean
import com.keyboard.craft.databinding.FragmentLikeBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LikeFragment : Fragment() {
    private lateinit var binding: FragmentLikeBinding
    private var adapter: KeyDetailsDataAdapter? = null
    private var contentBeans: MutableList<ItemDataBean> = mutableListOf()


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = FragmentLikeBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
    }

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

    private fun initView() {
        adapter = KeyDetailsDataAdapter(requireActivity(), contentBeans, "like")
        binding.rv.layoutManager = GridLayoutManager(requireActivity(), 2)
        binding.rv.adapter = adapter
    }

    private fun initData() {
        loadingPlay()
        binding.noDataLayout.visibility = View.GONE
        GlobalScope.launch {
            val beans = CraftApp.databaseManager.getAllItemDataBeanFiles()
            if (beans.isNotEmpty()) {
                contentBeans.clear()
                contentBeans.addAll(beans)
                withContext(Dispatchers.Main) {
                    loadingClose()
                    binding.noDataLayout.visibility = View.GONE
                }
            } else {
                withContext(Dispatchers.Main) {
                    loadingClose()
                    binding.noDataLayout.visibility = View.VISIBLE
                }
            }
        }
    }

    private fun loadingPlay() {
        binding.loadingLayout.visibility = View.VISIBLE
    }

    private fun loadingClose() {
        binding.loadingLayout.visibility = View.GONE
    }
}