package com.gh.gamecenter.gamedetail.accelerator

import androidx.room.Dao
import androidx.room.Query
import androidx.room.Upsert
import com.gh.gamecenter.feature.entity.AcctGameInfo
import com.gh.gamecenter.feature.entity.AcctRecord
import io.reactivex.Observable
import io.reactivex.Single

@Dao
interface AccelerationDao {

    @Upsert
    fun upsertAcctGameInfo(gameInfo: AcctGameInfo): Single<Long>

    @Upsert
    fun upsertAcctRecord(record: AcctRecord): Single<Long>

    /**
     * 为什么这里定义成 Observable<List<AcctGameInfo>> 而不是 Observable<AcctGameInfo>
     * 因为当返回值为 Observable<T> 时，当表中未查询到数据，则不会收到任何回调
     * 使用 Observable<List<AcctGameInfo>>时，为查询到数据时会返回空数组
     */
    @Query("SELECT * FROM AcctGameInfo WHERE gameId = :gameId")
    fun getAcctGameInfoByGameIdObservable(gameId: String): Observable<List<AcctGameInfo>>

    @Query("SELECT EXISTS(SELECT 1 FROM AcctGameInfo LIMIT 1)")
    fun hasAnyAcctGameInfo(): Single<Boolean>

    @Query("SELECT * FROM AcctGameInfo WHERE gameId IN (:gameIds)")
    fun queryAcctGameInfoByGameId(gameIds: List<String>): List<AcctGameInfo>

    @Query("SELECT * FROM AcctRecord ORDER BY createTime DESC LIMIT 20")
    fun loadAcctRecordsObservable(): Observable<List<AcctRecord>>

    @Query("SELECT * FROM AcctRecord ORDER BY createTime DESC LIMIT 20")
    fun loadAcctRecords(): List<AcctRecord>

    /**
     * 获取最新的记录（根据createTime排序）
     * @return 最新的AcctRecord记录
     */
    @Query("SELECT * FROM AcctRecord ORDER BY createTime DESC LIMIT 1")
    fun loadLatestRecord(): Single<AcctRecord>

    @Query("SELECT EXISTS(SELECT 1 FROM AcctRecord LIMIT 1)")
    fun getAnyAcctRecordObservable(): Observable<Boolean>
}