package it.integry.integrywmsnative.core.REST;

import android.util.Base64;

import java.io.IOException;

import it.integry.integrywmsnative.core.settings.SettingsManager;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by GiuseppeS on 06/03/2018.
 */

public class HttpInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        final String PROFILE_DB     = SettingsManager.i().userSession.profileDB;
        final String USERNAME       = SettingsManager.i().user.username;
        final String PASSWORD       = SettingsManager.i().user.password;

        final Request request = chain.request();
        final HttpUrl url = request.url().newBuilder()
                .addQueryParameter("profileDb", PROFILE_DB)
                .build();

        String string = "Basic " + Base64.encodeToString((USERNAME + ":" + PASSWORD).getBytes(), Base64.NO_WRAP);

        final Request newRequest = chain.request().newBuilder()
                .addHeader("Authorization", string)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "*/*")
                .addHeader("username", USERNAME != null ? USERNAME : "")
                .addHeader("password", PASSWORD != null ? PASSWORD : "")
                .url(url).build();

        return chain.proceed(newRequest);
    }
}
