package com.develop.food.base.http

import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import com.develop.food.base.api.response.BaseResult

/**
 * 多个网络请求封装
 */
class ComposeNetSource<T>(
    private val sourceData: Array<LiveData<ApiResponse<BaseResult<T>>>>,
    private val defaultData: T
) : MediatorLiveData<List<T>>() {

    private val composeData = mutableListOf<T>()
    private var composeDone = false
    private var successCount = 0

    init {
        for (liveData in sourceData) {
            composeData.add(defaultData)
        }
        for (index in sourceData.indices) {
            val liveData = sourceData[index]
            addSource(liveData) {
                it.data?.apply {
                    when {
                        isSuccess() -> {
                            it.data.let { model ->
                                model.data?.apply {
                                    composeData[index] = this
                                }
                            }
                            signalSingleDone()
                        }

                        tokenInvalidate() -> {
                            //token失效
                        }
                        else -> {
                            signalFailure()
                            return@addSource
                        }
                    }
                }
            }
        }
    }

    private fun signalFailure() {
        if (composeDone) {
            return
        }
        composeDone = true
        value = emptyList()
    }

    private fun signalSingleDone() {
        if (!composeDone && ++successCount == sourceData.size) {
            composeDone = true
            value = composeData.toList()
        }
    }
}