package com.paperapp.lenscape.preview

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.paperapp.lenscape.databinding.FragmentLikeWallpapersBinding
import com.paperapp.lenscape.tools.LikeWallpapersAdapter
import com.paperapp.lenscape.element.MainViewModel
import com.paperapp.lenscape.element.Element
import com.paperapp.lenscape.tools.SetLoveListener

class LikedWallpapersFragment : Fragment(),SetLoveListener {
    private lateinit var binding: FragmentLikeWallpapersBinding
    private lateinit var viewModel: MainViewModel
    private lateinit var adapter:LikeWallpapersAdapter
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding= FragmentLikeWallpapersBinding.inflate(inflater,container,false)
        init()
        return binding.root
    }
    private fun init(){
        viewModel=ViewModelProvider(requireActivity())[MainViewModel::class.java]
        adapter=LikeWallpapersAdapter()
        adapter.setListener(this)
        viewModel.likeElements.observe(viewLifecycleOwner) { element ->
            Log.d("LikeFragment","paper is$element")
            if (element.isNullOrEmpty()) {
                // 可以在这里显示空状态视图
                binding.layoutNoData.visibility = View.VISIBLE
                binding.rvView.visibility = View.GONE
            } else {
                binding.layoutNoData.visibility = View.GONE
                binding.rvView.visibility = View.VISIBLE
                adapter.setList(element)
                adapter.notifyDataSetChanged()
            }
        }
        val gridLayoutManager = GridLayoutManager(requireActivity(), 3)
        binding.rvView.layoutManager=gridLayoutManager
        binding.rvView.adapter=adapter
    }

    override fun inItemClick(paper: Element) {
        val intent= Intent(context, ImagePreviewActivity::class.java)
        intent.putExtra(ImagePreviewActivity.paperKey,paper)
        startActivity(intent)
    }
}