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

import android.util.Log
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 CoolWeatherNetwork {

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

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

    suspend fun fetchOrderList(requestBody: RequestBody) = orderService.getOrderList(requestBody).await()

    suspend fun updateRestOpenStatus(requestBody: RequestBody) = service.updateRestOpenStatus(requestBody).await()

    suspend fun getOrderInfo(requestBody: RequestBody) = orderService.getOrderDesc(requestBody).await()

    suspend fun updateOrderStatus(requestBody: RequestBody) = orderService.updateOrderStatus(requestBody).await()

    suspend fun updateSelfOrderStatus(requestBody: RequestBody) = orderService.updateSelfOrderStatus(requestBody).await()

    suspend fun getDeliveryInfo(requestBody: RequestBody) = orderService.getDeliveryInfo(requestBody).await()

    suspend fun getHistoryOrderList(requestBody: RequestBody) = orderService.getHistoryOrderList(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()
                    Log.e("eee", "請求地址：" + response.raw().request().url())
                    if (body != null) {
                        continuation.resume(body)
                    } else continuation.resumeWithException(RuntimeException("response body is null") as Throwable)
                }
            })
        }
    }

    companion object {

        private var network: CoolWeatherNetwork? = null

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

    }

}