package de.beyondsoft.ownchat.data.api;

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

import de.beyondsoft.ownchat.BewoplanerApplication;
import de.beyondsoft.ownchat.BuildConfig;
import de.beyondsoft.ownchat.data.AppPrefsConstants;
import de.beyondsoft.ownchat.data.prefs.StringPreference;
import de.beyondsoft.ownchat.di.P3DSEndpoint;
import de.beyondsoft.ownchat.di.scopes.ApplicationScope;
import de.beyondsoft.ownchat.utils.Constants;

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

import javax.inject.Named;

import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.schedulers.Schedulers;

/**
 * Created by laszloffiferenc on 2/21/17.
 */
@Module
public class ApiModule {

    @Provides
    @ApplicationScope
    Cache provideCache(BewoplanerApplication app) {
        File httpCacheDirectory = new File(app.getCacheDir().getAbsolutePath(), "HttpCache");
        return new Cache(httpCacheDirectory, Constants.DISK_CACHE_SIZE);
    }

    @Provides
    @ApplicationScope
    HttpLoggingInterceptor provideLoggingInterceptor() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        if (BuildConfig.DEBUG) {
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        } else {
            interceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
        }

        return interceptor;
    }

    @Provides
    @ApplicationScope
    Interceptor provideHeaderInterceptor(@Named(AppPrefsConstants.LOGIN_TOKEN) final StringPreference token, @Named(AppPrefsConstants.ACCOUNT_NO) final StringPreference customerId) {
        return chain -> {
            final boolean isHeaderSet = token.isSet() || customerId.isSet();
            Request original = chain.request();
            Request.Builder builder = original.newBuilder();
            if (token.isSet()) {
                builder.addHeader("Token", token.get());
            }

            if (customerId.isSet()) {
                builder.addHeader("CustomerID", customerId.get());
            }

            if (isHeaderSet) {
                return chain.proceed(builder.build());
            }

            return chain.proceed(original.newBuilder().build());
        };
    }

    @Provides
    @ApplicationScope
    @P3DSEndpoint
    OkHttpClient provideP3DSOkHttpClient(Cache cache, HttpLoggingInterceptor loggingInterceptor, Interceptor interceptor) {
        return new OkHttpClient.Builder()
                .cache(cache)
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                .addInterceptor(interceptor)
                .build();
    }

    @Provides
    @ApplicationScope
    CallAdapter.Factory provideCallAdapterFactory() {
        return RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
    }

    @Provides
    @ApplicationScope
    Gson provideGson() {
        return new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
    }

    @Provides
    @ApplicationScope
    Converter.Factory provideConverterFactory(Gson gson) {
        return GsonConverterFactory.create(gson);
    }

    @Provides
    @ApplicationScope
    @P3DSEndpoint
    Retrofit provideP3DSRetrofit(@P3DSEndpoint final OkHttpClient okHttpClient,
                                 @Named(AppPrefsConstants.API_ENDPOINT) final StringPreference endpoint,
                                 final Converter.Factory converter,
                                 final CallAdapter.Factory adapterFactory) {
        return new Retrofit.Builder()
                .baseUrl(endpoint.get() == null ? Constants.BEWOPLANER_ENDPOINT : endpoint.get())
                .addCallAdapterFactory(adapterFactory)
                .addConverterFactory(converter)
                .client(okHttpClient)
                .build();
    }
}