package com.vpn.fastestvpnservice.retrofit;

import com.vpn.fastestvpnservice.application.App;
import com.vpn.fastestvpnservice.constants.AppConstant;
import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper;
import com.vpn.fastestvpnservice.retrofit.entities.GsonFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class WebServiceFactory {

    final static String TAG = WebServiceFactory.class.getSimpleName();

    private static final String KEY_HEADER_AUTHORIZATION = "Authorization";
    private static final String X_PLATFORM = "X-PLATFORM";
    private static final String X_PLATFORM_TOKEN = "X-PLATFORM-TOKEN";
    private static final String PLATFORM = "platform";
    private static final String VERSION = "version";

    private static Api instance;
    private static Api instance2;

    public static Api getInstance() {

        BasePreferenceHelper prefHelper = new BasePreferenceHelper(App.getApplication());

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.connectTimeout(120, TimeUnit.SECONDS);
        httpClient.readTimeout(120, TimeUnit.SECONDS);

        if (instance == null) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            // TODO uncomment_this_JC
//            if (BuildConfig.DEBUG) {
//                logging.setLevel(HttpLoggingInterceptor.Level.BODY);
//            }

            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {

                    Request original = chain.request();
                    Request.Builder requestBuilder;
                    requestBuilder = original.newBuilder()
                            .header(X_PLATFORM, "android")
                            .header(KEY_HEADER_AUTHORIZATION, (prefHelper.getUser() != null) ? "Bearer " + prefHelper.getUser().getToken() : "")
                            .header(X_PLATFORM_TOKEN, (prefHelper.getXPlatformToken() != null) ? prefHelper.getXPlatformToken() : "");

                    return chain.proceed(requestBuilder.build());
                }
            });


            OkHttpClient client = httpClient.addInterceptor(logging).build();
            Retrofit retrofit = new Retrofit.Builder().baseUrl(AppConstant.BASE_URL).client(client).addConverterFactory(GsonConverterFactory.create(GsonFactory.getSimpleGson())).build();

            instance = retrofit.create(Api.class);
        }
        return instance;
    }

}