package com.keyboard.themes.key.fagment

import android.os.Bundle
import android.util.Log
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.themes.key.AppThemes
import com.keyboard.themes.key.api.CancelLikeCallback
import com.keyboard.themes.key.daapter.AdapterLiked
import com.keyboard.themes.key.data.MyData
import com.keyboard.themes.key.databinding.ThemeLayoutLikeFragmentBinding
import com.keyboard.themes.key.db.BaseDataBase
import com.keyboard.themes.key.db.DbAction
import kotlinx.coroutines.launch

class FragLike : Fragment() {
    private lateinit var vb: ThemeLayoutLikeFragmentBinding


    companion object {

        @JvmStatic
        fun newInstance() =
            FragLike()
    }

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

        init()

        return vb.root
    }


    private fun init() {
        val mainAdapter = AdapterLiked(
            requireContext()
        ).apply {
            setRemoveLike(object : CancelLikeCallback {
                override fun OnRemoveLike(data: MyData) {
                     lifecycleScope.launch {
                         DbAction.removeLike(data)
                     }
                }

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

        BaseDataBase.baseDataBase.ThemesDao().queryAllLike().observe(requireActivity()) {
            Log.d(AppThemes.TAG, "---------it=${it?.size}")
            if(it.isNullOrEmpty()){
                vb.likeRecycler.isVisible = false
                vb.emptyTitle.isVisible = true
            }else{
                vb.likeRecycler.isVisible = true
                vb.emptyTitle.isVisible = false
                mainAdapter.setForYouList(it)
            }

        }
    }


}