package com.gh.gamecenter.forum.search

import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.SearchActivity
import com.gh.gamecenter.SearchType
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadParams
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.feature.entity.AnswerEntity
import com.gh.gamecenter.feature.entity.ForumVideoEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Observable

class ForumContentSearchListViewModel(application: Application, val bbsId: String, private val location: String) :
    ListViewModel<AnswerEntity, AnswerEntity>(application) {
    var searchKey = ""
    var mSort = ""
    var sourceEntrance = ""
    private var mPage = 0
    private var mPageSize = 20
    private var mTotal = 0
    private var searchType = SearchType.DEFAULT.value

    var videoList = arrayListOf<ForumVideoEntity>()

    override fun provideDataObservable(page: Int): Observable<MutableList<AnswerEntity>>? {
        mPage = page
        if (page == 1) {
            NewFlatLogUtils.logSearchingContent(
                location,
                bbsId,
                SearchType.fromString(searchType).toChinese(),
                searchKey
            )
        }
        val map = hashMapOf("keyword" to searchKey, "sort" to mSort)
        if (bbsId.isNotEmpty()) {
            map["bbs_id"] = bbsId
        }
        return RetrofitManager.getInstance().api.searchForumContent(map, page, mPageSize)
            .map {
                mTotal = it.headers()["Total"]?.toInt() ?: 0
                it.body()
            }
    }

    override fun loadStatusControl(size: Int) {
        if (mCurLoadParams.loadOffset == LoadParams.DEFAULT_OFFSET) { // 初始化列表
            if (mTotal == 0) {
                mLoadStatusLiveData.setValue(LoadStatus.INIT_EMPTY)
            } else if (size == REQUEST_FAILURE_SIZE) {
                mLoadStatusLiveData.setValue(LoadStatus.INIT_FAILED)
            } else if (mTotal <= mPage * mPageSize) { // 避免一个屏幕出现两次分页
                mLoadStatusLiveData.setValue(LoadStatus.INIT_OVER)
            } else {
                mLoadStatusLiveData.setValue(LoadStatus.INIT_LOADED)
            }
        } else {
            if (size == REQUEST_FAILURE_SIZE) {
                mLoadStatusLiveData.setValue(LoadStatus.LIST_FAILED)
            } else if (mTotal <= mPage * mPageSize) {
                mLoadStatusLiveData.setValue(LoadStatus.LIST_OVER)
            } else {
                mLoadStatusLiveData.setValue(LoadStatus.LIST_LOADED)
            }
        }

        if (size == REQUEST_FAILURE_SIZE) {
            mRetryParams = mCurLoadParams
        } else {
            mRetryParams = null
            mCurLoadParams.loadOffset = mCurLoadParams.loadOffset + 1 // 页数 + 1
        }
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) {
            videoList = ArrayList(it.map { answer ->
                answer.transformForumVideoEntity()
            })

            mResultLiveData.postValue(it)

            if (mPage == 1) {
                SensorsBridge.trackArticleSearchResultReturn(
                    GlobalActivityManager.getCurrentPageEntity().pageId,
                    GlobalActivityManager.getCurrentPageEntity().pageName,
                    sourceEntrance,
                    searchKey,
                    SearchActivity.toTrackSearchType(searchType),
                    it.isNotEmpty()
                )
            }
        }
    }

    fun updateSearchKeyAndType(searchKey: String, searchType: String) {
        this.searchKey = searchKey
        this.searchType = searchType
        load(LoadType.REFRESH)
    }

    fun updateSort(sort: String) {
        mSort = sort
        load(LoadType.REFRESH)
    }

    fun getLinkPageSize(): Int {
        return mCurLoadParams.loadOffset
    }

    class Factory(private val bbsId: String, private val location: String) : ViewModelProvider.NewInstanceFactory() {

        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return ForumContentSearchListViewModel(HaloApp.getInstance().application, bbsId, location) as T
        }
    }
}