package com.gh.gamecenter.toolbox

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.core.utils.GsonUtils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.common.utils.toJson
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.entity.ToolBoxBlockEntity
import com.gh.gamecenter.common.entity.ToolBoxEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.google.gson.reflect.TypeToken
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import retrofit2.HttpException

class ToolBoxViewModel(application: Application) : AndroidViewModel(application) {

    var mSearchKey = "" //搜索关键字

    val toolBoxBlockList = MutableLiveData<List<ToolBoxBlockEntity>>()
    val searchResultList = MutableLiveData<List<ToolBoxEntity>>()
    val loadStatus = MutableLiveData<LoadStatus>()
    val searchStatus = MutableLiveData<LoadStatus>()

    fun getToolBoxList() {
        RetrofitManager.getInstance().newApi.categoryToolKits
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<List<ToolBoxBlockEntity>>() {
                override fun onResponse(response: List<ToolBoxBlockEntity>?) {
                    super.onResponse(response)
                    response?.let {
                        if (SPUtils.getString(Constants.TOOLBOX_HISTORY).isNotEmpty()) {
                            toolBoxBlockList.postValue(getNewList(it))
                        } else {
                            toolBoxBlockList.postValue(it)
                        }
                    }
                    loadStatus.postValue(if (response.isNullOrEmpty()) LoadStatus.INIT_EMPTY else LoadStatus.INIT_LOADED)
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    loadStatus.postValue(LoadStatus.INIT_FAILED)
                }
            })
    }

    // 添加最近使用列表
    fun getNewList(list: List<ToolBoxBlockEntity>): List<ToolBoxBlockEntity> {
        val historyList = getHistoryList()
        return if (historyList.isNotEmpty()) arrayListOf(
            ToolBoxBlockEntity(
                categoryName = "最近使用",
                toolboxList = historyList
            )
        ).apply {
            addAll(list)
        } else list
    }

    fun getHistoryList(): List<ToolBoxEntity> {
        if (SPUtils.getString(Constants.TOOLBOX_HISTORY).isEmpty()) return emptyList()
        try {
            val historyList: List<ToolBoxEntity> = GsonUtils.gson.fromJson(
                SPUtils.getString(Constants.TOOLBOX_HISTORY),
                object : TypeToken<ArrayList<ToolBoxEntity>>() {}.type
            )
            val validList = arrayListOf<ToolBoxEntity>().apply {
                // 最多展示30天以内的打开记录
                for (item in historyList) {
                    val offsetDay = TimeUtils.getBeforeDays(item.lastOpenTime / 1000)
                    if (offsetDay <= 30) {
                        add(item)
                    }
                }
            }
            SPUtils.setString(Constants.TOOLBOX_HISTORY, validList.take(4).toJson())
            return validList.take(4)
        } catch (e: Exception) {
            return emptyList()
        }
    }

    fun addToHistoryList(entity: ToolBoxEntity) {
        val historyList = ArrayList(getHistoryList())
        val newList = historyList.apply {
            if (contains(entity)) remove(entity)
            add(0, entity.apply { lastOpenTime = System.currentTimeMillis() })
        }
        SPUtils.setString(Constants.TOOLBOX_HISTORY, newList.take(4).toJson())
    }

    fun getSearchResultList() {
        RetrofitManager.getInstance().newApi.getToolKits(mSearchKey)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<List<ToolBoxEntity>>() {
                override fun onResponse(response: List<ToolBoxEntity>?) {
                    super.onResponse(response)
                    response?.let {
                        when {
                            it.isEmpty() -> {
                                searchStatus.postValue(LoadStatus.INIT_EMPTY)
                            }
                            else -> {
                                searchStatus.postValue(LoadStatus.INIT_LOADED)
                                searchResultList.postValue(it)
                            }
                        }
                    }
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    searchStatus.postValue(LoadStatus.INIT_FAILED)
                }
            })
    }

    fun getGameToolBoxData(gameId: String, callback: (toolboxList: List<ToolBoxEntity>) -> Unit) {
        RetrofitManager.getInstance()
            .api
            .getGameToolBoxData(1, UrlFilterUtils.getFilterQuery("game_id", gameId))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<List<ToolBoxEntity>>() {
                override fun onResponse(response: List<ToolBoxEntity>?) {
                    if (response == null) return
                    callback.invoke(response)
                }
            })
    }
}