package com.keyboard.keyboardtheme.skin.frag

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.keyboard.keyboardtheme.skin.adapter.AdaFavorite
import com.keyboard.keyboardtheme.skin.databinding.FragmentFavoriteBinding
import com.keyboard.keyboardtheme.skin.datamanager.db.DbManager
import com.keyboard.keyboardtheme.skin.datamanager.db.RoomBase
import com.keyboard.keyboardtheme.skin.datamanager.localdata.Child
import com.keyboard.keyboardtheme.skin.utils.OnUpdateFavorite
import kotlinx.coroutines.launch

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

    private lateinit var adaFavorite: AdaFavorite


    companion object {

        @JvmStatic
        fun newInstance() =
            FragFavorite()
    }

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

        init()

        return vb.root
    }


    private fun init() {
        adaFavorite = AdaFavorite(
            requireContext()
        ).apply {
            setRemoveLike(object : OnUpdateFavorite {
                override fun onRemoveLike(data: Child) {
                     lifecycleScope.launch {
                         DbManager.removeLike(data)
                     }
                }

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

        RoomBase.myroom.ThemesDao().queryAllLike().observe(requireActivity()) {
            if(it.isNullOrEmpty()){
                vb.likeRecycler.isVisible = false
                vb.emptyTitle.isVisible = true
            }else{
                vb.likeRecycler.isVisible = true
                vb.emptyTitle.isVisible = false
                adaFavorite.setForYouList(it)
            }

        }
    }



}