package com.gh.gamecenter.collection

import android.annotation.SuppressLint
import android.app.Application
import com.gh.gamecenter.core.AppExecutor
import com.gh.common.history.HistoryDatabase
import com.gh.common.history.HistoryHelper
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.feature.entity.AnswerEntity
import com.gh.gamecenter.feature.entity.ArticleEntity
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import retrofit2.HttpException

class CommunityArticleViewModel(application: Application) : ListViewModel<ArticleEntity, ArticleEntity>(application) {

    var type: String = CommunityArticleFragment.Type.COLLECTION.value

    override fun provideDataObservable(page: Int): Observable<MutableList<ArticleEntity>>? {
        return null
    }

    override fun provideDataSingle(page: Int): Single<List<ArticleEntity>> {
        return if (type == CommunityArticleFragment.Type.COLLECTION.value) {
            Single.fromObservable(
                RetrofitManager.getInstance().api
                    .getCollectionArticleAndQuestion(UserManager.getInstance().userId, page)
                    .flatMap(Function<List<AnswerEntity>, Observable<List<ArticleEntity>>> { list ->
                        Observable.create { emitter ->
                            val articleList = list.map { it.transformArticleEntity() }.toList()
                            emitter.onNext(articleList)
                            emitter.onComplete()
                        }
                    })
            )
        } else {
            if (page > 5) {
                Single.create { it.onSuccess(arrayListOf()) }
            } else {
                HistoryDatabase.instance.articleDao().getArticleWithOffset(20, (page - 1) * 20)
            }
        }
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource<List<ArticleEntity>>(mListLiveData) { mResultLiveData.postValue(it) }
    }

    fun removeHistory(articleEntity: ArticleEntity) {
        mResultLiveData.value?.let {
            HistoryHelper.deleteArticleEntity(articleEntity.id)

            it.remove(articleEntity)
            if (it.size == 0) {
                AppExecutor.uiExecutor.executeWithDelay(Runnable { load(LoadType.REFRESH) }, 100)
            } else {
                mResultLiveData.postValue(it)
            }
        }
    }

    fun removeHistories(ids: List<String>) {
        mResultLiveData.value?.let { datas ->
            ids.forEach { id ->
                HistoryHelper.deleteArticleEntity(id)
                val entity = datas.find { it.id == id }
                datas.remove(entity)
            }

            if (datas.size == 0) {
                AppExecutor.uiExecutor.executeWithDelay(Runnable { load(LoadType.REFRESH) }, 100)
            } else {
                mResultLiveData.postValue(datas)
            }
        }
    }

    fun deleteCollection(communityId: String, articleId: String) {
        RetrofitManager.getInstance().api
            .deleteCommunityArticleFavorites(articleId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    Utils.toast(getApplication(), R.string.collection_cancel)

                    val value = mResultLiveData.value
                    if (value != null) {
                        for (i in 0 until value.size) {
                            val data = value[i]
                            if (data.id == articleId) {
                                value.remove(data)
                                mResultLiveData.postValue(value)
                                break
                            }
                        }
                    }
                }

                override fun onFailure(e: HttpException?) {
                    Utils.toast(getApplication(), R.string.collection_cancel_failure)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun postCollectionArticleRead(communityId: String, articleId: String) {
        RetrofitManager.getInstance().api
            .postCollectionArticleRead(UserManager.getInstance().userId, communityId, articleId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                }
            })
    }
}