package com.gh.gamecenter.mygame

import android.annotation.SuppressLint
import android.app.Application
import com.gh.common.repository.ReservationRepository
import com.gh.gamecenter.core.runOnUiThread
import com.gh.gamecenter.common.utils.createRequestBody
import com.gh.download.DownloadManager
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.retrofit.BiResponse
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.schedulers.Schedulers
import okhttp3.ResponseBody

class MyReservationViewModel(application: Application) : ListViewModel<GameEntity, GameEntity>(application) {

    var positionAndPackageMap = HashMap<String, Int>() // key: packageName + position, value: position

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

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

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) {
            positionAndPackageMap.clear()
            it.forEachIndexed { index, gameEntity ->
                gameEntity.hideSizeInsideDes = true
                addGamePositionAndPackage(gameEntity, index)
            }
            mResultLiveData.postValue(it)
        }
    }

    private fun addGamePositionAndPackage(game: GameEntity, position: Int) {
        var packages = ""
        for (apkEntity in game.getApk()) {
            packages += apkEntity.packageName
        }
        packages += game.simulator?.apk?.packageName
        positionAndPackageMap[packages + position] = position
        game.setEntryMap(DownloadManager.getInstance().getEntryMap(game.name))
    }

    @SuppressLint("CheckResult")
    fun deleteReservation(game: GameEntity) {
        deleteOrCancelReservation(game, true)
    }

    fun cancelReservation(game: GameEntity) {
        deleteOrCancelReservation(game, false)
    }

    @SuppressLint("CheckResult")
    private fun deleteOrCancelReservation(game: GameEntity, deleteReservation: Boolean) {
        val requestMap = hashMapOf<String, String>()
        requestMap["game_id"] = game.id

        val single = if (deleteReservation) {
            RetrofitManager.getInstance().api
                .deleteGameReservation(requestMap.createRequestBody())
                .subscribeOn(Schedulers.io())
        } else {
            RetrofitManager.getInstance().api
                .cancelGameReservation(requestMap.createRequestBody())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
        }

        single.subscribe(object : BiResponse<ResponseBody>() {
            override fun onSuccess(data: ResponseBody) {
                ReservationRepository.refreshReservations()

                if (deleteReservation) {
//                    MtaHelper.onEvent("预约游戏", "取消预约", game.name)
                } else {
//                    MtaHelper.onEvent("预约游戏", "删除预约", game.name)
                }

                val list = mListLiveData.value
                // 当数据量为1的时候不删了，直接刷新
                if (list?.size == 1) {
                    runOnUiThread { load(LoadType.REFRESH) }
                } else {
                    list?.remove(list.find { it.id == game.id })
                    mListLiveData.postValue(list)
                }
            }

            override fun onFailure(exception: Exception) {
                Utils.toast(getApplication(), exception.message)
                exception.printStackTrace()
            }
        })
    }

}