package com.soundapp.soundgags.ui

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.soundapp.soundgags.databinding.FragmentSaveItemsBinding
import com.soundapp.soundgags.setting.FavSolidAdapter
import com.soundapp.soundgags.datame.Reflection
import com.soundapp.soundgags.datame.MainViewModel
import com.soundapp.soundgags.setting.LikeUpClickListener

class SavedItemsFragment(viewModel: MainViewModel) : Fragment(),LikeUpClickListener {
    private lateinit var binding: FragmentSaveItemsBinding

    private lateinit var adapter: FavSolidAdapter
    private val mainViewModel: MainViewModel = viewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        binding = FragmentSaveItemsBinding.inflate(inflater, container, false)
        initView()
        return binding.root
    }

    override fun onResume() {
        super.onResume()
        Log.d("CollectFragment", "onResume: ")
        mainViewModel.loadLikeItems()
        mainViewModel.loadCustomItems()
    }

    private fun initView() {
        adapter = FavSolidAdapter()
        adapter.setListener(this)
        mainViewModel.likeItems.observe(viewLifecycleOwner){likeList ->
            Log.d("CollectFragment", "initView: $likeList")
            if(likeList.isEmpty()){
                binding.emptyView.visibility=View.VISIBLE
                binding.recyclerView.visibility=View.GONE
            }else{
                binding.emptyView.visibility=View.GONE
                binding.recyclerView.visibility=View.VISIBLE
                adapter.setList(likeList,0)
                adapter.notifyDataSetChanged()
            }
        }

        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager=LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL,false)
    }

    override fun onMoreClick(reflection: Reflection,isAdd: Boolean) {
        mainViewModel.updateLikeStatus(reflection.name,!isAdd)
    }

}