package com.gingersoft.gsa.other_order_mode.data.network

import com.gingersoft.gsa.other_order_mode.data.network.api.DeliveryService
import com.gingersoft.gsa.other_order_mode.data.network.api.WeatherService
import okhttp3.RequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

class DeliveryNetwork {

    private val orderService = ServiceCreator.create(DeliveryService::class.java)

    private val service = ServiceCreator.create2(DeliveryService::class.java)

    private val gsposService = ServiceCreator.create3(DeliveryService::class.java)

    //獲取物流配置
    suspend fun queryDeliveryList(requestBody: RequestBody) = gsposService.queryDeliveryList(requestBody).await()

    //獲取物流配置
    suspend fun addDeliveryList(requestBody: RequestBody) = gsposService.addDeliveryList(requestBody).await()

    //獲取物流配置
    suspend fun updateDelivery(requestBody: RequestBody) = gsposService.updateDelivery(requestBody).await()



    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onFailure(call: Call<T>, t: Throwable) {
                    t.printStackTrace()
                    continuation.resumeWithException(t)
                }

                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) {
                        continuation.resume(body)
                    } else continuation.resumeWithException(RuntimeException("response body is null") as Throwable)
                }
            })
        }
    }

    companion object {

        private var network: DeliveryNetwork? = null

        fun getInstance(): DeliveryNetwork {
            if (network == null) {
                synchronized(DeliveryNetwork::class.java) {
                    if (network == null) {
                        network = DeliveryNetwork()
                    }
                }
            }
            return network!!
        }

    }

}