package com.key.board.journey.inputmethod.fragment

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.key.board.journey.inputmethod.myInter.InterfaceUpdateLike
import com.key.board.journey.inputmethod.data.ChildBean
import com.key.board.journey.inputmethod.databinding.FragmentFavoriteBinding
import com.key.board.journey.inputmethod.mydata.BaseDataBase
import com.key.board.journey.inputmethod.mydata.DbHelper
import com.key.board.journey.inputmethod.list.ItemFavorite
import kotlinx.coroutines.launch

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

    private lateinit var itemFavorite: ItemFavorite


    companion object {

        @JvmStatic
        fun newInstance() =
            FavoriteFragment()
    }

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

        init()

        return vb.root
    }


    private fun init() {
        itemFavorite = ItemFavorite(
            requireContext()
        ).apply {
            setRemoveLike(object : InterfaceUpdateLike {
                override fun onRemoveLike(data: ChildBean) {
                     lifecycleScope.launch {
                         DbHelper.removeLike(data)
                     }
                }

            })
        }
        vb.likeRecycler.run {
            adapter = itemFavorite
            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
                itemFavorite.setForYouList(it)
            }

        }
    }



}