package com.keypalette.theme

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.keypalette.theme.dataabout.database.LikeFunction
import com.keypalette.theme.dataabout.database.RoomBase
import com.keypalette.theme.dataabout.resource.Data
import com.keypalette.theme.databinding.FragmentLikeBinding
import com.keypalette.theme.other.listener.ListenerLike
import kotlinx.coroutines.launch

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

    private lateinit var likeAdapter: LikeAdapter


    companion object {

        @JvmStatic
        fun newInstance() =
            FragmentLike()
    }

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

        init()

        return vb.root
    }


    private fun init() {
        likeAdapter = LikeAdapter(
            requireContext()
        ).apply {
            setRemoveLike(object : ListenerLike {
                override fun onRemoveLike(data: Data) {
                     lifecycleScope.launch {
                         LikeFunction.removeLike(data)
                     }
                }

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

        RoomBase.Companion.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
                likeAdapter.setForYouList(it)
            }

        }
    }



}