package com.getbubblenow.android.api.network;

import com.getbubblenow.android.api.interceptor.AcceptInterceptor;
import com.getbubblenow.android.api.interceptor.UserAgentInterceptor;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public final class ClientService {
    private static volatile ClientService clientService;
    private Retrofit retrofit;

    private ClientService() {

    }

    public static ClientService getInstance() {
        if (clientService == null) {
            synchronized (ClientService.class) {
                if (clientService == null) {
                    clientService = new ClientService();
                }
            }
        }
        return clientService;
    }

    public <T> T getErrorBodyAs(final ResponseBody responseBody, final Type type) throws IOException {
        final Converter<ResponseBody, T> converter = retrofit.responseBodyConverter(type, new Annotation[0]);
        return converter.convert(responseBody);
    }

    public ClientApi createClientApi(final String url) {

        final OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.addInterceptor(interceptor);

        httpClient.addInterceptor(new AcceptInterceptor());
        httpClient.addInterceptor(new UserAgentInterceptor(System.getProperty("http.agent")));

        retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(httpClient.build())
                .build();

        return retrofit.create(ClientApi.class);
    }
}
