package it.integry.integrywmsnative.core.rest;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

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, SettingsManager.i().getServer().getHost(), SettingsManager.i().getServer().getPort(), true);

    }
    public static <T> T getService(final Class<T> service, int timeout) {
        return getService(service, SettingsManager.i().getServer().getHost(), SettingsManager.i().getServer().getPort(), true, true, timeout);

    }

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

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

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

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

        clientBuilder.retryOnConnectionFailure(true);

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

        OkHttpClient client = clientBuilder.build();

        String endpoint = "http://" + host + ":" + port + "/" + (addEmsApi ? "ems-api/" : "");

        Gson gson = new GsonBuilder()
                .setDateFormat("dd/MM/yyyy HH:mm:ss")
                .create();

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

        return retrofit.create(service);
    }
}
