package com.ys.bdtp.adm.mvvm.model.nt

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext


/**
 * 网络请求
 *
 * @param request 请求方法
 * @return [Response] 请求结果封装
 */
suspend fun <T> request(request: suspend () -> Model<T>): Response<T> {
    return withContext(Dispatchers.IO) {
        try {
            val model = request()
            if (model.result == "success") {
                Response.create(model.data)
            } else {
                Response.create(Fail(model.result, model.message ?: "request ok, but no data"))
            }
        } catch (t: Throwable) {
            Response.create(Fail("catch", t.message ?: "request catch and nothing"))
        }
    }
}

/**
 * 网络请求
 *
 * @param request 请求数据
 * @param success 请求成功
 * @param failure 请求失败
 *
 */
suspend fun <T> request(
    request: suspend () -> Model<T>,
    success: suspend (T) -> Unit,
    failure: (Fail) -> Unit,
) {
    withContext(Dispatchers.IO) {
        runCatching {
            request()
        }.onSuccess {
            if (it.result == "success") {
                success(it.data)
            } else {
                failure(Fail(it.result, it.message ?: "request ok, but no data"))
            }
        }.onFailure {
            failure(Fail("catch", it.message ?: "request catch and nothing"))
        }
    }
}