package com.assimilate.alltrans.http;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    private static boolean instanced = false;
    private volatile static RetrofitClient retrofitClient;

    private Retrofit retrofit;

    private RetrofitClient() {
        synchronized (RetrofitClient.class) {
            if (instanced) {
                throw new RuntimeException("Instance multiple RetrofitClient.");
            } else {
                instanced = true;
            }
            if (retrofitClient != null) {
                throw new RuntimeException("Instance multiple RetrofitClient.");
            }
            initRetrofitClient();
        }
    }

    public static RetrofitClient getInstance() {
        if (retrofitClient == null) {
            synchronized (RetrofitClient.class) {
                if(retrofitClient == null) {
                    retrofitClient = new RetrofitClient();
                }
            }
        }
        return retrofitClient;
    }

    private void initRetrofitClient() {
        final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();

        final Retrofit.Builder builder = new Retrofit.Builder();
        builder.client(okHttpClient);
        builder.baseUrl("https://translate.google.com/")
                .addConverterFactory(GsonConverterFactory.create());
        builder.callbackExecutor(Executors.newSingleThreadExecutor());
        this.retrofit = builder.build();
    }

    public Retrofit getRetrofitClient() {
        return retrofit;
    }
}
