package com.develop.main.init.ui

import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.develop.food.base.common.*
import com.develop.food.base.data.DataFactory
import com.develop.food.base.data.model.FoodContentModel
import com.develop.food.base.event.RefreshDataEvent
import com.develop.food.base.repo.CURRENT_USER_ID
import com.develop.food.base.repo.FoodDataProvider
import com.develop.food.base.repo.entity.DevRecipe
import com.develop.food.base.router.Screens
import com.develop.food.base.router.navigateTo
import com.develop.food.base.ui.BaseActivity
import com.develop.food.base.utils.ResDimension
import com.develop.food.base.utils.ThreadUtils
import com.develop.main.R
import com.develop.main.databinding.ActivityFoodListBinding
import com.develop.main.init.ui.adapter.RecipesListAdapter
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

@Route(path = Screens.Main.FOOD_LIST)
class FoodListActivity : BaseActivity<ActivityFoodListBinding>() {
    private var recipesListAdapter = RecipesListAdapter()
    var title: String = ""
    var foodListType = Favourite
    private var dataList = mutableListOf<FoodContentModel>()
    override fun createViewBinding(inflater: LayoutInflater): ActivityFoodListBinding {
        return ActivityFoodListBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        EventBus.getDefault().register(this)
        val bundle = intent.extras
        title = bundle?.getString(FOOL_LIST_TITLE) ?: ""
        foodListType = bundle?.getInt(FOOD_LIST_TYPE) ?: Favourite
        binding.topBar.setTopBarTitle(title)
        binding.topBar.listenBackClick {
            finish()
        }
        recipesListAdapter.isHistory = foodListType == History
        binding.foodListRecycler.apply {
            adapter = recipesListAdapter
            addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    super.getItemOffsets(outRect, view, parent, state)
                    val pos = parent.getChildAdapterPosition(view)
                    if (pos == 0) {
                        outRect.top = ResDimension(R.dimen.convert_30px).toInt()
                    }
                }
            })
        }

        recipesListAdapter.setOnItemClickListener { adapter, view, position ->
            val recipesContent = dataList[position]
            navigateTo(Screens.Cook.COOK_DETAIL) {
                withString(
                    "source", if (recipesContent.isNetRecipes) {
                        "remote"
                    } else {
                        "local"
                    }
                )
                withString("number", recipesContent.foodId)
                withBoolean("isLike", recipesContent.isLike)
            }
        }

    }

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

    override fun onDestroy() {
        super.onDestroy()
//        EventBus.getDefault().unregister(this)
    }

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

    private fun refreshData() {
        if (foodListType == Downloaded) {
            getOnLineDownloadedFoodList()
        } else {
            getFavoriteOrHistoryFoodList(foodListType)
        }
    }

    private fun getFavoriteOrHistoryFoodList(foodListType: Int) {
        ThreadUtils.runOnWorkThread({
            val userDao = FoodDataProvider.getUserDatabase().userInfoDao()
            val recipesDao = FoodDataProvider.getDatabase().recipeDao()
            val recipesIdList = mutableListOf<String>()
            val favoriteRecipesIds = mutableListOf<String>()
            if(foodListType == Favourite){
                userDao.queryFavoriteRecipes(CURRENT_USER_ID).forEach {
                    recipesIdList.add(it.favoriteRecipesId)
                    favoriteRecipesIds.add(it.favoriteRecipesId)
                }
            }

            if (foodListType == History) {
                userDao.queryHistoryRecipes(CURRENT_USER_ID).forEach {
                    recipesIdList.add(it.historyRecipesId)
                }
            }
            val recipesList = mutableListOf<DevRecipe>()
            recipesIdList.forEach {
                recipesDao.queryRecipe(it)?.apply {
                    recipesList.add(this)
                }
            }
            dataList.clear()
            recipesList.forEach {
                dataList.add(
                    FoodContentModel(
                        it.photoPath ?: "",
                        it.name ?: "",
                        3,
                        DataFactory.getTime(it.makeHours ?: 0, it.makeMinutes ?: 0),
                        it.difficultyLevel ?: "",
                        isLike = favoriteRecipesIds.contains(it.number),
                        foodId = it.number ?: "",
                        recipesEdition = it.edition
                    )
                )
            }
            ThreadUtils.runOnMainThread {
                recipesListAdapter.setList(dataList)
            }
        })
    }


    private fun getOnLineDownloadedFoodList() {
        ThreadUtils.runOnWorkThread({
            val userDao = FoodDataProvider.getUserDatabase().userInfoDao()
            val recipesDao = FoodDataProvider.getDatabase().recipeDao()
            val recipesIdList = mutableListOf<String>()
            val favoriteRecipesIds = mutableListOf<String>()
            userDao.queryFavoriteRecipes(CURRENT_USER_ID).forEach {
//                recipesIdList.add(it.favoriteRecipesId)
                favoriteRecipesIds.add(it.favoriteRecipesId)
            }
            userDao.queryUserOnLineRecipesIds().forEach {
                recipesIdList.add(it.onLineRecipesId)
            }
            val recipesList = mutableListOf<DevRecipe>()
            recipesIdList.forEach {
                recipesDao.queryRecipe(it)?.apply {
                    recipesList.add(this)
                }
            }
            dataList.clear()
            recipesList.forEach {
                dataList.add(
                    FoodContentModel(
                        it.photoPath ?: "",
                        it.name ?: "",
                        3,
                        DataFactory.getTime(it.makeHours ?: 0, it.makeMinutes ?: 0),
                        it.difficultyLevel ?: "",
                        isLike = favoriteRecipesIds.contains(it.number),
                        foodId = it.number ?: "",
                        isNetRecipes = true,
                        hasDownloaded = true,
                        recipesEdition = it.edition
                    )
                )
            }
            ThreadUtils.runOnMainThread {
                recipesListAdapter.setList(dataList)
            }
        })
    }


}