package http;

import java.util.Objects;

import http.client.retrofit.ApiService;
import http.converter.NullOnEmptyConverterFactory;
import http.interceptor.TokenHeaderInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import xn.xxp.app.LabApp;
import xn.xxp.room.RoomTool;
import xn.xxp.room.bean.DeviceConfig;

public class HttpClient {
    private static okhttp3.OkHttpClient okHttpClient;
    private static Retrofit retrofit;
    private static ApiService apiService;

    public static ApiService createRetrofitApi(Class<ApiService> apiServiceClass) {
        return Objects.requireNonNullElseGet(apiService, () -> apiService = buildRetrofit().create(apiServiceClass));
    }

    public static Retrofit buildRetrofit() {
        DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
        if (null != retrofit) {
            return retrofit;
        } else {
            Retrofit.Builder builder = new Retrofit.Builder();
            builder.client(buildHttpClient());
            builder.baseUrl(deviceConfig.getBaseUrl());
            builder.addCallAdapterFactory(RxJava3CallAdapterFactory.create());
            builder.addConverterFactory(new NullOnEmptyConverterFactory());
            builder.addConverterFactory(GsonConverterFactory.create(LabApp.gson));
            return retrofit = builder.build();
        }
    }

    public static okhttp3.OkHttpClient buildHttpClient() {
        if (null != okHttpClient) {
            return okHttpClient;
        } else {
            okhttp3.OkHttpClient.Builder builder = new okhttp3.OkHttpClient.Builder();
            builder.addNetworkInterceptor(new TokenHeaderInterceptor());
            return okHttpClient = builder.build();
        }
    }

}
