package com.gh.gamecenter.mygame

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody

open class PlayedGameViewModel(application: Application, var userId: String, val isKeepTagStyle: Boolean = false) :
    ListViewModel<GameEntity, GameEntity>(application) {

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

    override fun provideDataSingle(page: Int): Single<MutableList<GameEntity>> {
        return RetrofitManager.getInstance().api.getPlayedGames(userId, page, Utils.getTime(getApplication()), mapOf())
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) {
            if (!isKeepTagStyle) {
                it.forEach { game ->
                    game.hideSizeInsideDes = true
                    game.tagStyle.clear()
                }
            }
            mResultLiveData.postValue(it)
        }
    }

    @SuppressLint("CheckResult")
    fun deletePlayedGame(gameEntity: GameEntity) {
        RetrofitManager.getInstance().api
            .deletePlayedGame(userId, gameEntity.playedGameId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    mListLiveData.value?.let {
                        for (game in it) {
                            if (gameEntity.id == game.id) {
                                it.remove(game)
                                mListLiveData.postValue(it)
                                break
                            }
                        }
                    }
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    Utils.toast(getApplication(), exception.localizedMessage)
                }
            })
    }

    class Factory(private val mUserId: String, val isKeepTagStyle: Boolean = false) :
        ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return PlayedGameViewModel(HaloApp.getInstance().application, mUserId, isKeepTagStyle) as T
        }
    }

}