/*
 * Copyright 2017 .
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dinect.checker.net;

import java.io.IOException;

import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author anonymous
 */
public final class DinectAuthorizationInterceptor implements Interceptor {

    private final String token;
    private final String appToken;

    private final String dmAuthorization;
    private final String authorization;
    private final String userAgent;
    private final boolean useAuthHeader;

    public DinectAuthorizationInterceptor(final String appToken, final String token, final String clientInfo, final boolean useAuthHeader) {
        this.appToken = appToken;
        this.token = token;
        this.useAuthHeader = useAuthHeader;
        userAgent = clientInfo;
        // optimization: concatenate once
        dmAuthorization = "dmapptoken " + appToken;
        authorization = "dmtoken " + token;
    }

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

        final Request originalRequest = chain.request();
        final HttpUrl originalUrl = originalRequest.url();
        final Request.Builder requestBuilder = originalRequest.newBuilder();

        HttpUrl url = originalUrl;
        Headers headers;

        headers = originalRequest.headers();
        final Headers.Builder headersBuilder = headers.newBuilder();
        // always set UA and content type
        headersBuilder.set("User-Agent", userAgent);

        // Add auth info. Either in headers or query parameters
        if (useAuthHeader) {
            headersBuilder.set("DM-Authorization", dmAuthorization);
            if (null != token) {
                headersBuilder.set("Authorization", authorization);
            }
            headers = headersBuilder.build();
        } else {
            final HttpUrl.Builder urlBuilder = originalRequest.url().newBuilder();
            urlBuilder.addQueryParameter("_dmapptoken", appToken);
            urlBuilder.addQueryParameter("user_agent", userAgent);
            if (null != token) {
                urlBuilder.addQueryParameter("_dmtoken", token);
            }
            url = urlBuilder.build();
        }

        final Request request = requestBuilder.url(url).headers(headers).build();
        return chain.proceed(request);
    }
}