package com.develop.food.base.http

import androidx.lifecycle.*
import com.develop.food.base.api.response.BaseResult
import okhttp3.MultipartBody
import okhttp3.RequestBody

/**
 * 无状态回调
 */
fun <T> LiveData<Resource<T>>.observeSingle(
    owner: LifecycleOwner = ProcessLifecycleOwner.get(),
    observer: Observer<Resource<T>>
) {
    observe(owner, object : Observer<Resource<T>> {
        override fun onChanged(t: Resource<T>?) {
            if (t != null && t.status != Resource.Status.LOADING) {
                removeObserver(this)
            }
            observer.onChanged(t)
        }
    })
}

/**
 * 有状态回调
 */
fun <T> LiveData<Resource<T>>.observeStatus(
    owner: LifecycleOwner = ProcessLifecycleOwner.get(),
    onLoading: (() -> Unit)? = null,
    onSuccess: ((data: T?) -> Unit)? = null,
    onFailed: ((error: ErrorMsg?) -> Unit)? = null,
) {
    observe(owner, object : Observer<Resource<T>> {
        override fun onChanged(t: Resource<T>?) {
            if (t != null && t.status != Resource.Status.LOADING) {
                removeObserver(this)
            }
            if (t == null) {
                return
            }
            when (t.status) {
                Resource.Status.LOADING -> onLoading?.invoke()
                Resource.Status.SUCCESS -> onSuccess?.invoke(t.data)
                Resource.Status.FAILURE -> onFailed?.invoke(t.data as ErrorMsg)
            }
        }
    })
}

fun <T> checkDataAndSignal(
    signalLiveData: MutableLiveData<Resource<T>>,
    sourceLiveData: LiveData<ApiResponse<BaseResult<T>>>,
    forceUpdate: Boolean = true
) {
    if (!forceUpdate && shouldSkipFetchRemote(signalLiveData.value)) {
        return
    }
    signalLiveData.value = Resource.loading()
    sourceLiveData.observeForever {
        it.data?.apply {
            when {
                isSuccess() -> {
                    signalLiveData.value = Resource.success(getRespContent())
                }
                tokenInvalidate() -> {

                }
                else -> {
                    signalLiveData.value =
                        Resource.failure(ErrorMsg(status, getError() ?: "UnKnowError"))
                }
            }
        }
    }
}

fun shouldSkipFetchRemote(resource: Resource<*>?): Boolean {
    return resource != null
            && (resource.status == Resource.Status.SUCCESS
            || resource.status == Resource.Status.LOADING)
}

fun Map<String, String>.generateMultipartBody(): RequestBody {
    val requestDataMap = this
    val builder = MultipartBody.Builder()
    builder.setType(MultipartBody.FORM)//表单类型
    requestDataMap.forEach {
        builder.addFormDataPart(it.key, it.value)
    }
    return builder.build()
}