package com.wall.photography.wallpaper.activivty

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.wall.photography.wallpaper.MyApp
import com.wall.photography.wallpaper.R
import com.wall.photography.wallpaper.adapter.AdapterHomePaing
import com.wall.photography.wallpaper.data.Bean
import com.wall.photography.wallpaper.databinding.ActivityListBinding
import com.wall.photography.wallpaper.databinding.ActivityMainBinding
import com.wall.photography.wallpaper.fragment.HomeViewModel
import com.wall.photography.wallpaper.manager.MyItemDecoration
import com.wall.photography.wallpaper.topon.AdManager
import com.wall.photography.wallpaper.viewmode.ListActivityViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class ListActivity : AppCompatActivity() {
    private lateinit var vb: ActivityListBinding

    companion object {
        const val KEY = "category_name"
    }

    private lateinit var viewModel: ListActivityViewModel
    private lateinit var adapterHomepaging: AdapterHomePaing
    private lateinit var name: String
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        vb = ActivityListBinding.inflate(layoutInflater)
        AdManager.loadAllAd()
        setContentView(vb.root)
        viewModel = ViewModelProvider(this)[ListActivityViewModel::class.java]
        name = intent.getStringExtra(KEY)!!
        vb.tvName.text = name
        vb.back.setOnClickListener {
            AdManager.showTopOn(this@ListActivity) {
                finish()
            }
        }
        adapterHomepaging = AdapterHomePaing(mContext = this@ListActivity) {
            AdManager.showTopOn(this@ListActivity) {
                startActivity(Intent(this, SetWallpaperActivity::class.java).apply {
                    putExtra(SetWallpaperActivity.KEY_DATA, it)
                    putExtra(SetWallpaperActivity.KEY_MAIN_ENTER, false)
                })
            }
        }
        CoroutineScope(Dispatchers.Main).launch {
            viewModel.getPagingData(name).collectLatest {
                Log.d(MyApp.TAG, "------------collectLatest ")
                adapterHomepaging.submitData(it)
            }
        }
        initWallpaper()

    }

    override fun onBackPressed() {
        super.onBackPressed()
        AdManager.showTopOn(this@ListActivity) {

        }
    }

    private fun initWallpaper() {
        vb.list.run {
            layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
            adapter = adapterHomepaging
            addItemDecoration(MyItemDecoration(this@ListActivity, 8, 8, 0))
        }

    }
}