package com.adpro.pixelshow.look

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity

import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.adpro.pixelshow.event.MoreAndSearchAdapter

import com.adpro.pixelshow.data.MainViewModel
import com.adpro.pixelshow.data.Movie
import com.adpro.pixelshow.databinding.ActivityTypeInfoBinding
import com.adpro.pixelshow.event.SecFavListener
import com.adpro.pixelshow.util.TopBarUtils

class TypeInfoActivity : AppCompatActivity(),SecFavListener {
    private lateinit var binding:ActivityTypeInfoBinding
    private lateinit var viewModel: MainViewModel
    private lateinit var adapter:MoreAndSearchAdapter
    private var currentTitleName: String = ""


    companion object{
        var titleName:String="name"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding=ActivityTypeInfoBinding.inflate(layoutInflater)
        init()
        TopBarUtils.setStatusBar(this.window)
        TopBarUtils.setLightStatusBar(this.window,true)
        setContentView(binding.root)
    }
    private fun init(){
        viewModel=ViewModelProvider(this)[MainViewModel::class.java]
        currentTitleName = intent?.getStringExtra(titleName) ?: "Default Title"
        // 保存标题到ViewModel
        viewModel.currentTitleName = currentTitleName

        // 设置标题 - 从ViewModel获取确保数据持久化
        binding.name.text = viewModel.currentTitleName ?: currentTitleName
        binding.searchPb.visibility= View.VISIBLE
        binding.imageBack.setOnClickListener { finish() }
        adapter=MoreAndSearchAdapter()
        adapter.setListener(this)
        binding.list.layoutManager=GridLayoutManager(this,2)
        binding.list.adapter=adapter
        viewModel.classificationList.observe(this) { list ->
            // 在这里处理返回的数据
            if(list.isNotEmpty()){
                updateUI(list)
            }
        }
        if(viewModel.classificationList.value.isNullOrEmpty()){
            Log.d("Therererer","startGet")
            viewModel.getClassificationList(currentTitleName)
        }
    }
    private fun updateUI(list: List<Movie>){
        Log.d("MoreMovieActivity","list size is"+list.size.toString())
        adapter.setList(list)
        binding.searchPb.visibility= View.GONE
        adapter.notifyDataSetChanged()
    }

    override fun inItemClick(paper: Movie) {
        val intent= Intent(this,DownloadRequestActivity::class.java)
        intent.putExtra(DownloadRequestActivity.paperKey,paper)
        startActivity(intent)
    }
}