package com.cartoon.wallpapers.live.ui

import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cartoon.wallpapers.live.ada.Like
import com.cartoon.wallpapers.live.base.BaseActivity
import com.cartoon.wallpapers.live.databinding.ActivityFavoriteBinding
import com.cartoon.wallpapers.live.topon.AdManager
import com.cartoon.wallpapers.live.utils.ObjectBoxManager
import com.cartoon.wallpapers.live.utils.Decoration
import com.cartoon.wallpapers.live.vm.ViewModelLike
import io.objectbox.reactive.DataSubscription

class FavoriteActivity : BaseActivity<ActivityFavoriteBinding>() {

    private var dataSubscription: DataSubscription? = null

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

        v?.let {
            if (v == vb.ivBack) {
                AdManager.showTopOn(this@FavoriteActivity){
                    finish()
                }

            }
        }


    }

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

    override fun onCreateInit() {
        AdManager.loadAllAd()
        val likeAdapter = Like(this)
        vb.recycler.run {
            adapter = likeAdapter
            layoutManager = GridLayoutManager(
                this@FavoriteActivity,
                2,
                RecyclerView.VERTICAL,
                false
            )
            addItemDecoration(
                Decoration(
                    this@FavoriteActivity,
                    8,
                    8,
                    8
                )
            )
        }


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

        viewModelLike!!.likeLiveData.observe(
            this@FavoriteActivity
        ) {
            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)
        }

        AdManager.showTopOn(this@FavoriteActivity)

    }

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

    override fun isFullScreen(): Boolean = true

    override fun statusBarLight(): Boolean = true


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