package com.keyboard.skinning.cool.fragment

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.keyboard.skinning.cool.App
import com.keyboard.skinning.cool.adpter.AdapterFavorite
import com.keyboard.skinning.cool.data.ChildData
import com.keyboard.skinning.cool.databinding.FragmentFavoriteBinding
import com.keyboard.skinning.cool.db.BaseDataBase
import com.keyboard.skinning.cool.db.DbFunction
import com.keyboard.skinning.cool.listener.RemoveFavoriteListener
import kotlinx.coroutines.launch

class FragmentFavorite : Fragment() {
    private lateinit var vb: FragmentFavoriteBinding


    companion object {

        @JvmStatic
        fun newInstance() =
            FragmentFavorite()
    }

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

        init()

        return vb.root
    }


    private fun init() {
        val mainAdapter = AdapterFavorite(
            requireContext()
        ).apply {
            setRemoveLike(object : RemoveFavoriteListener {
                override fun OnRemoveLike(data: ChildData) {
                     lifecycleScope.launch {
                         DbFunction.removeLike(data)
                     }
                }

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

        BaseDataBase.baseDataBase.ThemesDao().queryAllLike().observe(requireActivity()) {
            Log.d(App.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)
            }

        }
    }


}