package com.develop.step.ui


import android.os.Bundle
import android.view.LayoutInflater
import com.alibaba.android.arouter.facade.annotation.Route
import com.develop.base.ext.resId2Dimension
import com.develop.base.ext.updateText
import com.develop.common.data_repo.db.FoodContentModel
import com.develop.common.event.RefreshDataEvent
import com.develop.common.router.Screens
import com.develop.common.ui.CommonBVMActivity
import com.develop.common.widget.FoodContentView
import com.develop.common.R
import com.develop.common.tag.*
import com.develop.step.databinding.ActivityFoodListBinding
import com.develop.step.viewmodel.FoodListViewModel
import com.drake.brv.utils.grid
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

@Route(path = Screens.Cook.FOOD_LIST)
class FoodListActivity : CommonBVMActivity<ActivityFoodListBinding, FoodListViewModel>() {
    private var title: String = ""

    override fun createViewModel(): FoodListViewModel {
        return getViewModel(FoodListViewModel::class.java)
    }

    override fun createViewBinding(inflater: LayoutInflater): ActivityFoodListBinding {
        return ActivityFoodListBinding.inflate(inflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val bundle = intent.extras
        binding.ivClose.setOnClickListener {
            finish()
        }
        viewModel.foodListType = bundle?.getInt(FOOD_LIST_TYPE) ?: Favourite
        title = bundle?.getString(FOOL_LIST_TITLE) ?: ""
        binding.tvTitle.updateText(title)
        binding.foodListRecycler.apply {
            grid(4)
            setup {
                addType<FoodContentModel>(R.layout.food_content_provider)
                onBind {
                    val foodContentView =
                        findView<FoodContentView>(R.id.food_content_view)
                    foodContentView.mIsHistoryList = viewModel.foodListType == History
                    foodContentView.setFoodContent(getModel(), true)
                }
            }
        }.models = viewModel.foodListLiveData.value

        viewModel.foodListLiveData.observe(this) {
            binding.foodListRecycler.models = it
            if (viewModel.foodListType == Downloaded) {
                title = "$title(${it.size})"
                binding.tvTitle.updateText(title)
            }
        }
    }

    @Subscribe
    fun onRefreshDataEvent(event: RefreshDataEvent) {
        viewModel.refreshData()
    }

    override fun onResume() {
        super.onResume()
        viewModel.refreshData()
    }

    override fun onDestroy() {
        super.onDestroy()

    }

    companion object {
        var dp30 = (com.develop.base.R.dimen.convert_30px).resId2Dimension().toInt()
    }
}