package it.integry.integrywmsnative.core.REST;

import java.util.concurrent.TimeUnit;

import it.integry.integrywmsnative.core.settings.SettingsManager;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by GiuseppeS on 06/03/2018.
 */

public class RESTBuilder {

    public static <T> T getService(final Class<T> service) {
//        return getService(service, "192.168.2.13", 8080);
        return getService(service, SettingsManager.i().server.host, SettingsManager.i().server.port, true);

    }
    public static <T> T getService(final Class<T> service, int timeout) {
//        return getService(service, "192.168.2.13", 8080);
        return getService(service, SettingsManager.i().server.host, SettingsManager.i().server.port, true, timeout);

    }
    public static <T> T getService(final Class<T> service, String host, int port, boolean addInterceptors) {
        return getService(service, host, port, addInterceptors, 30);
    }

    public static <T> T getService(final Class<T> service, String host, int port, boolean addInterceptors, int timeout){
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();

        clientBuilder.connectTimeout(timeout, TimeUnit.SECONDS);
        clientBuilder.readTimeout(timeout, TimeUnit.SECONDS);
        clientBuilder.writeTimeout(timeout, TimeUnit.SECONDS);

        if(addInterceptors) clientBuilder.addInterceptor(new HttpInterceptor());

        OkHttpClient client = clientBuilder.build();

        String endpoint = "http://" + host + ":" + port + "/ems-api/";

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(endpoint)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();



        return retrofit.create(service);
    }
}
