package com.gh.common.repository

import android.annotation.SuppressLint
import com.gh.common.util.CheckLoginUtils
import com.gh.gamecenter.login.user.UserManager
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.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * 预约游戏仓库，存储了用户已预约的游戏列表
 */
object ReservationRepository {

    private var mReservationSet = hashSetOf<String>()

    @JvmStatic
    fun refreshReservationsIfNeeded() {
        if (mReservationSet.isEmpty()) {
            refreshReservations()
        }
    }

    fun addReservationToMemoryAndRefresh(gameId: String) {
        mReservationSet.add(gameId)
        refreshReservations()
    }

    @JvmStatic
    fun removeReservationFromMemoryAndRefresh(gamedId: String) {
        mReservationSet.remove(gamedId)
        refreshReservations()
    }

    @SuppressLint("CheckResult")
    @JvmStatic
    fun refreshReservations() {
        if (CheckLoginUtils.isLogin()) {
            RetrofitManager.getInstance().api
                .getAllTheGameReservations(
                    UserManager.getInstance().userId,
                    Utils.getTime(HaloApp.getInstance().application)
                )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : BiResponse<List<String>>() {

                    override fun onSuccess(data: List<String>) {
                        mReservationSet = HashSet(data)
                    }

                })
        }
    }

    @JvmStatic
    fun clearReservations() {
        mReservationSet.clear()
    }

    @JvmStatic
    fun thisGameHasBeenReserved(gameId: String): Boolean {
        return if (!CheckLoginUtils.isLogin()) false else {
            if (mReservationSet.isEmpty()) {
                false
            } else {
                mReservationSet.contains(gameId)
            }
        }
    }

}