package com.rich.keyboard.skin.uifragment

import android.os.Bundle
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.rich.keyboard.skin.callback.OnUpdateLikeBack
import com.rich.keyboard.skin.databinding.FragLikeBinding
import com.rich.keyboard.skin.db.BaseDataBase
import com.rich.keyboard.skin.db.DbTool
import com.rich.keyboard.skin.listadapter.LikeList
import com.rich.keyboard.skin.localdata.Child
import kotlinx.coroutines.launch

class LikeFragmentUi : Fragment() {
    private lateinit var vb: FragLikeBinding

    private lateinit var likeList: LikeList


    companion object {

        @JvmStatic
        fun newInstance() =
            LikeFragmentUi()
    }

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

        init()

        return vb.root
    }


    private fun init() {
        likeList = LikeList(
            requireContext()
        ).apply {
            setRemoveLike(object : OnUpdateLikeBack {
                override fun onRemoveLike(data: Child) {
                     lifecycleScope.launch {
                         DbTool.removeLike(data)
                     }
                }

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

        BaseDataBase.baseDataBase.ThemesDao().queryAllLike().observe(requireActivity()) {
            if(it.isNullOrEmpty()){
                vb.likeRecycler.isVisible = false
                vb.emptyTitle.isVisible = true
            }else{
                vb.likeRecycler.isVisible = true
                vb.emptyTitle.isVisible = false
                likeList.setForYouList(it)
            }

        }
    }



}