package com.keyborad.theme.trendyborad.trendyuifragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.keyborad.theme.trendyborad.TrendyApp
import com.keyborad.theme.trendyborad.bean.BeanDetails
import com.keyborad.theme.trendyborad.databinding.FragmentFavoriteKeyboardBinding
import com.keyborad.theme.trendyborad.database.BaseDataBase
import com.keyborad.theme.trendyborad.database.DatabaseManager
import com.keyborad.theme.trendyborad.trendycallback.TrendyDeleteFavoriteCallback
import com.keyborad.theme.trendyborad.trendylistutils.TrendyFavoriteAdapter
import kotlinx.coroutines.launch

class TrendyFragmentFavoriteKeyboard : Fragment() {
    private lateinit var vb: FragmentFavoriteKeyboardBinding
    companion object {

        @JvmStatic
        fun newInstance() =
            TrendyFragmentFavoriteKeyboard()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        vb = FragmentFavoriteKeyboardBinding.inflate(layoutInflater)

        init()

        return vb.root
    }


    private fun init() {
        val mainAdapter = TrendyFavoriteAdapter(
            requireContext()
        ).apply {
            setRemoveLike(object : TrendyDeleteFavoriteCallback {
                override fun OnRemoveLike(data: BeanDetails) {
                     lifecycleScope.launch {
                         DatabaseManager.removeLike(data)
                     }
                }

            })
        }
        vb.likeRecycler.run {
            adapter = mainAdapter
            layoutManager = GridLayoutManager(requireContext(), 2)
        }

        BaseDataBase.Companion.baseDataBase.ThemesDao().queryAllLike().observe(requireActivity()) {
            Log.d(TrendyApp.Companion.TAG, "---------it=${it?.size}")
            if(it.isNullOrEmpty()){
                vb.likeRecycler.isVisible = false
                vb.emptyTitle.isVisible = true
            }else{
                vb.likeRecycler.isVisible = true
                vb.emptyTitle.isVisible = false
                mainAdapter.setForYouList(it)
            }

        }
    }


}