package com.gh.gamecenter.gamedetail.fuli.kaifu

import android.app.Application
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.entity.HaloAddonEntity
import com.gh.gamecenter.feature.entity.ServerCalendarFormEntity
import com.gh.gamecenter.feature.entity.ServerCalendarGame
import com.gh.gamecenter.retrofit.RetrofitManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import io.reactivex.Observable
import io.reactivex.Single

class ServersCalendarListViewModel(application: Application) :
    ListViewModel<ServersCalendarListViewModel.ItemData, ServersCalendarListViewModel.ItemData>(
        application
    ) {

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

    override fun provideDataSingle(page: Int): Single<MutableList<ItemData>> {
        return RetrofitManager.getInstance().newApi
            .getServerCalendarList(page, 20)
            .map { list ->
                val dataList = mutableListOf<ItemData>()
                for (formEntity in list) {
                    dataList.add(ItemData(time = formEntity.startMidnight))
                    dataList.addAll(formEntity.games.map { game ->
                        ItemData(game = game.apply {
                            startMidnight = formEntity.startMidnight
                        })
                    })
                }
                dataList
            }
    }

    fun getTimeByPosition(position: Int): Long {
        var time = 0L
        val dataList = mResultLiveData.value

        dataList?.let {
            for ((index, value) in dataList.withIndex()) {
                if (value.time != null) {
                    time = value.time
                }
                if (index == position) {
                    return time
                }
            }
        }
        return time
    }

    fun getItemAtPosition(position: Int): ItemData? {
        if (position < (mResultLiveData?.value?.size ?: 0)) {
            return mResultLiveData.value?.get(position)
        }
        return null
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) { list ->
            mResultLiveData.postValue(
                mutableListOf<ItemData>()
                    .also {
                        it.addAll(list)
                        it.add(ItemData(footer = true))
                    }
            )
        }
    }

    data class ItemData(val game: ServerCalendarGame? = null, val time: Long? = null, val footer: Boolean = false)
}