package com.fusi24.entryPermitScanner.data.api;

import android.content.Context;

import androidx.annotation.NonNull;

import com.fusi24.entryPermitScanner.BuildConfig;
import com.fusi24.entryPermitScanner.config.Constant;
import com.fusi24.entryPermitScanner.data.SessionManager;
import com.fusi24.entryPermitScanner.data.interceptor.RestHeaderModifierInterceptor;
import com.fusi24.entryPermitScanner.util.Helper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

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

public class RestServiceFactory {

    public static RestService create(String token, String userId, Context context) {
        OkHttpClient client = makeClientService(makeLoggingInterceptor(), token, userId, context);
        return makeRestService(client, makeGson(), context);
    }

    private static RestService makeRestService(OkHttpClient okHttp, Gson gson, Context context) {

        Retrofit retrofit;
        SessionManager session = new SessionManager(Helper.getDefaultPreferences(context));
        if (session.isDevelopment()){
            retrofit = new Retrofit.Builder()
                    .baseUrl(Constant.BASE_URL_DEV)
                    .client(okHttp)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        } else {
            retrofit = new Retrofit.Builder()
                    .baseUrl(Constant.BASE_URL_PROD)
                    .client(okHttp)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return retrofit.create(RestService.class);
    }

    @NonNull
    private static OkHttpClient makeClientService(
            HttpLoggingInterceptor loggingInterceptor, String token, String userId, Context context) {
        return new OkHttpClient.Builder()
                .addInterceptor(new RestHeaderModifierInterceptor(token, userId, context))
                .addInterceptor(loggingInterceptor)
                .build();
    }

    @NonNull
    private static HttpLoggingInterceptor makeLoggingInterceptor() {
        return new HttpLoggingInterceptor()
                .setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY
                        : HttpLoggingInterceptor.Level.NONE);
    }

    @NonNull
    private static Gson makeGson() {
        return new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
    }

}
