package com.free.video.wallpaper.uipage

import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.free.video.wallpaper.baseapp.MyBaseActivity
import com.free.video.wallpaper.databinding.PageFavoriteBinding
import com.free.video.wallpaper.helper.MyItemDecoration
import com.free.video.wallpaper.helper.ObjectBoxManager
import com.free.video.wallpaper.mylist.LikeAdapter
import com.free.video.wallpaper.vmhelper.ViewModelLike
import io.objectbox.reactive.DataSubscription

class PageFavorite : MyBaseActivity<PageFavoriteBinding>() {

    private var dataSubscription: DataSubscription? = null

    private var viewModelLike: ViewModelLike? = null
    override fun onClick(v: View?) {

        v?.let {
            if(v == vb.ivBack){
                finish()
            }
        }


    }

    override fun getViewBinding(): PageFavoriteBinding = PageFavoriteBinding.inflate(layoutInflater)

    override fun onCreateInit() {

        val likeAdapter = LikeAdapter(this)
        vb.recycler.run {
            adapter = likeAdapter
            layoutManager = GridLayoutManager(
                this@PageFavorite,
                2,
                RecyclerView.VERTICAL,
                false
            )
            addItemDecoration(
                MyItemDecoration(
                    this@PageFavorite,
                    8,
                    8,
                    8
                )
            )
        }


        viewModelLike = getActivityScopeViewModel<ViewModelLike>(
            ViewModelLike::class.java)

        viewModelLike!!.likeLiveData.observe(
            this@PageFavorite
        ) {
            likeAdapter.submitData(lifecycle, it)
        }
        dataSubscription = ObjectBoxManager.setLikeUpdateListener { data ->
            if (data.size == 0) {
                vb.layoutEmpty.visibility = View.VISIBLE
            } else {
                vb.layoutEmpty.visibility = View.GONE
            }
            viewModelLike!!.update(data)
        }

    }

    override fun onInitClick() {
        vb.ivBack.setOnClickListener(this)
    }

    override fun isFullScreen(): Boolean = true

    override fun statusBarLight(): Boolean = false


    override fun onDestroy() {
        super.onDestroy()
        if (dataSubscription != null) {
            dataSubscription!!.cancel()
        }
    }
}