package com.themes.keyboard.black.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.themes.keyboard.black.recycler.AdapterLike
import com.themes.keyboard.black.databinding.FragmentLikeBinding
import com.themes.keyboard.black.databasemanager.BaseDataBase
import com.themes.keyboard.black.databasemanager.DbHelper
import com.themes.keyboard.black.listener.OnUpdateLikeListener
import com.themes.keyboard.black.localdata.ChildData
import kotlinx.coroutines.launch

class LikeFragment : Fragment() {
    private lateinit var vb: FragmentLikeBinding

    private lateinit var adapterLike: AdapterLike


    companion object {

        @JvmStatic
        fun newInstance() =
            LikeFragment()
    }

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

        init()

        return vb.root
    }


    private fun init() {
        adapterLike = AdapterLike(
            requireContext()
        ).apply {
            setRemoveLike(object : OnUpdateLikeListener {
                override fun onRemoveLike(data: ChildData) {
                     lifecycleScope.launch {
                         DbHelper.removeLike(data)
                     }
                }

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

        }
    }



}