package com.apps.pixwall.view

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.apps.pixwall.R
import com.apps.pixwall.adapter.ThreeLineAdapter
import com.apps.pixwall.data.MainViewModel
import com.apps.pixwall.data.Paper
import com.apps.pixwall.databinding.FragmentFavoriteBinding
import com.apps.pixwall.listener.MainInListener

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

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