package mobos.leoss.si.qsystemmobileapp.Comunnication;

import android.app.Activity;

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

import java.util.Date;

import mobos.leoss.si.qsystemmobileapp.Interceptors.RequestInterceptor;
import mobos.leoss.si.qsystemmobileapp.SupportClasses.DateDeserializer;
import mobos.leoss.si.qsystemmobileapp.SupportClasses.DateSerializer;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
 * Created by janez on 1.3.2016.
 */
public class WebService {

    public static <S> S createService(Class<S> serviceClass, String apiEndPoint, Activity activity) {
        //String serviceEndpoint = "http://10.103.154.200/Android/WMSDebug/WMSServiceImpl.svc/";
        String serviceEndpoint = apiEndPoint;

        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
        clientBuilder.interceptors().add(new RequestInterceptor(activity));

        //dodamo Date converterja
        DateSerializer serializer = new DateSerializer();
        DateDeserializer deserializer = new DateDeserializer();
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Date.class, deserializer)
                .registerTypeAdapter(Date.class, serializer)
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                //url pot
                .baseUrl(serviceEndpoint)
                //gson converter
                .addConverterFactory(GsonConverterFactory.create(gson))
                //da retrofit zna sodelovati z RxJava klici (Observable namesto Call)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                //okHttp klient (tu lahko nastavimo read timeout, protokole,...
                .client(clientBuilder.build())
                .build();

        return retrofit.create(serviceClass);
    }
}

