package com.gh.gamecenter.energy.view

import android.annotation.SuppressLint
import android.app.Application
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.energy.entity.TaskEntity
import com.gh.gamecenter.energy.retrofit.RetrofitManager
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class TaskViewModel(application: Application) : ListViewModel<TaskEntity, TaskItemData>(application) {

    init {
        setOverLimitSize(1000) // 该页面不需要分页
    }

    private val mApi = RetrofitManager.getInstance().api
    private var mIsFirst = true
    private var mNoviceTasks = ArrayList<TaskEntity>()
    private var mFixedTasks = ArrayList<TaskEntity>()

    override fun provideDataObservable(page: Int) = null

    override fun provideDataSingle(page: Int): Single<List<TaskEntity>> {
        return mApi.getDailyTasks()
    }

    @SuppressLint("CheckResult")
    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) { list ->

            val itemDataList = arrayListOf<TaskItemData>()

            Single.concat(mApi.getNoviceTasks(), mApi.getFixedTasks())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (mIsFirst) {
                        mIsFirst = false
                        mNoviceTasks = ArrayList(it)
                    } else {
                        mIsFirst = true
                        mFixedTasks = ArrayList(it)
                    }
                }, {}, {
                    if (mNoviceTasks.isNotEmpty()) {
                        itemDataList.add(TaskItemData(noviceTasks = mNoviceTasks))
                    }

                    itemDataList.add(TaskItemData(title = "日常任务"))
                    list.forEach {
                        itemDataList.add(TaskItemData(dailyTask = it))
                    }
                    itemDataList.add(TaskItemData(bottom = mFixedTasks.isEmpty()))

                    if (mFixedTasks.isNotEmpty()) {
                        itemDataList.add(TaskItemData(title = "常驻任务"))
                        mFixedTasks.forEach {
                            it.isFixed = true
                            itemDataList.add(TaskItemData(dailyTask = it))
                        }
                        itemDataList.add(TaskItemData(bottom = true))
                    }

                    mResultLiveData.postValue(itemDataList)
                })
        }
    }
}