package com.develop.food.base.http.adapter

import androidx.lifecycle.LiveData
import com.develop.food.base.http.ApiResponse
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Callback
import retrofit2.Response
import java.lang.reflect.Type
import java.util.concurrent.atomic.AtomicBoolean


class LiveDataCallAdapter<T>(private val responseType: Type) : CallAdapter<T, LiveData<T>> {
    override fun adapt(call: Call<T>): LiveData<T> {
        return object : LiveData<T>() {
            private val started = AtomicBoolean(false)
            override fun onActive() {
                super.onActive()
                if (started.compareAndSet(false, true)) { //确保执行一次
                    call.enqueue(object : Callback<T> {
                        override fun onFailure(call: Call<T>, t: Throwable) {
                            val result = ApiResponse<T>(null, -999, t.message) as T
                            postValue(result)
                        }

                        override fun onResponse(call: Call<T>, response: Response<T>) {
                            val apiResponse =
                                ApiResponse(
                                    response.body(),
                                    response.code(),
                                    response.message()
                                ) as T
                            postValue(apiResponse)
                        }

                    })
                }
            }
        }
    }

    override fun responseType(): Type {
        return responseType
    }
}