package com.color.keyboard.black.myfragment

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.color.keyboard.black.adapter.AdapterLike
import com.color.keyboard.black.bean.ChildData
import com.color.keyboard.black.database.BaseDataBase
import com.color.keyboard.black.database.DbHelper
import com.color.keyboard.black.databinding.LayoutFragmentLikeBinding
import com.color.keyboard.black.myapi.OnCancelLikeApi
import kotlinx.coroutines.launch

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


    companion object {

        @JvmStatic
        fun newInstance() =
            FragmentLike()
    }

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

        init()

        return vb.root
    }


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

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

        }
    }


}