package ch.pizzalemon.android.api;

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

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

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import ch.pizzalemon.android.BuildConfig;
import ch.pizzalemon.android.activity.BaseActivity;
import ch.pizzalemon.android.helper.SessionHelper;
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 ApiService {

    private static ApiService apiService = new ApiService();
    public static ApiInterface apiInterface;
    public static Retrofit retrofit;

    private ApiService() { reset();}

    public static ApiService getInstance() {
        return apiService;
    }

    public void reset() {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();


        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.readTimeout(ApiConstants.API_READ_TIMEOUT, TimeUnit.SECONDS);
        builder.connectTimeout(ApiConstants.API_CONNECT_TIMEOUT, TimeUnit.SECONDS);

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

                Request.Builder builder = chain.request().newBuilder();
                builder.addHeader("Content-Type", "application/json");
                builder.addHeader("application", ApiConstants.APP_TYPE_ID_ANDROID);
                builder.addHeader("version", getAppVersionCode());

                String url = chain.request().url().toString();
                if(!url.contains("getSessionId") && !SessionHelper.getSessionId().isEmpty()){
                    builder.addHeader("session_id", SessionHelper.getSessionId());
                    //String cookie = "language=de-DE; currency=CHF; PHPSESSID=" + SessionHelper.getSessionId() + ";";
                    String cookie = "PHPSESSID=" + SessionHelper.getSessionId() + ";";
                    builder.addHeader("Cookie", cookie);
                }

                Request request = builder.build();
                return chain.proceed(request);
            }
        });

        addSSLTrustToOkHttp(builder);

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();  // set your desired log level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        if(BuildConfig.DEBUG){
            builder.addInterceptor(logging);
        }

        OkHttpClient client = builder.build();

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

        apiInterface = retrofit.create(ApiInterface.class);
    }

    private String getAppVersionCode(){
        try{
            int versionCode = BaseActivity.currentActivity.getAppVersionCode();
            return String.valueOf(versionCode);
        }
        catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }

    private void addSSLTrustToOkHttp(OkHttpClient.Builder okHttpClientBuilder) {
        try {
            SSLTrustManager trustManager = new SSLTrustManager();
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{ trustManager }, new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            okHttpClientBuilder.sslSocketFactory(sslSocketFactory, trustManager);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}