package com.app.input.breeze.board.uifragment

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.app.input.breeze.board.App
import com.app.input.breeze.board.bean.KeyboardTheme
import com.app.input.breeze.board.databinding.FragmentFavoriteKeyboardBinding
import com.app.input.breeze.board.database.AppDatabase
import com.app.input.breeze.board.database.FavoriteRepository
import com.app.input.breeze.board.callback.RemoveFavoriteCallback
import com.app.input.breeze.board.listutils.FavoriteThemeAdapter
import com.app.input.breeze.board.utils.BreezeTextView
import kotlinx.coroutines.launch

class FavoriteKeyboardFragment : Fragment() {
    private lateinit var vb: FragmentFavoriteKeyboardBinding
    companion object {

        @JvmStatic
        fun newInstance() =
            FavoriteKeyboardFragment()
    }

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

        init()

        return vb.root
    }


    private fun init() {
        val mainAdapter = FavoriteThemeAdapter(
            requireContext()
        ).apply {
            setRemoveLike(object : RemoveFavoriteCallback {
                override fun OnRemoveLike(data: KeyboardTheme) {
                     lifecycleScope.launch {
                         FavoriteRepository.removeLike(data)
                     }
                }

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

        AppDatabase.instance.favoriteThemeDao().queryAllLike().observe(requireActivity()) { favorites ->
            Log.d(App.Companion.TAG, "---------it=${favorites?.size}")
            if(favorites.isNullOrEmpty()){
                vb.likeRecycler.isVisible = false
                vb.emptyTitle.isVisible = true
            }else{
                vb.likeRecycler.isVisible = true
                vb.emptyTitle.isVisible = false
                mainAdapter.setForYouList(favorites)
            }

        }
    }


}