package com.joyful.euphoria.board.frag

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.joyful.euphoria.board.EuphoriaBoard
import com.joyful.euphoria.board.beaned.BeanDetails
import com.joyful.euphoria.board.database.BoardDataBase
import com.joyful.euphoria.board.assistant.DatabaseAssistant
import com.joyful.euphoria.board.remember.DeleteCollectRemember
import com.joyful.euphoria.board.recyclerview.RecyclerviewCollect
import kotlinx.coroutines.launch
import com.joyful.euphoria.board.databinding.FragCollectBinding
class FragmentCollect : Fragment() {
    private lateinit var vb: FragCollectBinding
    companion object {

        @JvmStatic
        fun newInstance() =
            FragmentCollect()
    }

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

        init()

        return vb.root
    }


    private fun init() {
        val mainAdapter = RecyclerviewCollect(
            requireContext()
        ).apply {
            setRemoveLike(object : DeleteCollectRemember {
                override fun OnRemoveLike(data: BeanDetails) {
                     lifecycleScope.launch {
                         DatabaseAssistant.removeLike(data)
                     }
                }

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

        BoardDataBase.Companion.boardDataBase.ThemesDao().queryAllLike().observe(requireActivity()) {
            Log.d(EuphoriaBoard.Companion.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)
            }

        }
    }


}