package tech.starwin.network;


import java.io.IOException;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import tech.starwin.LibConfig;
import tech.starwin.utils.LogUtils;
import tech.starwin.utils.LoginManager;
import tech.starwin.utils.PreferencesManager;
import tech.starwin.utils.collection.UploadManager;
import tech.starwin.utils.context_utils.AppInfoUtils;

/**
 * Created by XLEO on 2018/1/30.
 */

public class FirebaseHeaderInterceptor implements Interceptor {
    public static final String TAG = "FirebaseHeaderInterceptor";

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

        Request newRequest = chain.request();

        try {
            if (newRequest != null) {

                Request.Builder builder = chain.request().newBuilder();
                LogUtils.d(TAG,"android_id: "+ AppInfoUtils.getAndroidID(LibConfig.getContext()));
                builder.addHeader("X-REFERRER", PreferencesManager.get().getInstallReferrer())
                        .addHeader("X-REFERRER-SDK", PreferencesManager.get().getInstallReferrerFromSDK())
                        .addHeader("X-ANDROID-ID", AppInfoUtils.getAndroidID(LibConfig.getContext()));

                //登录后的上传
                if (!existHeader(newRequest.headers(), "X-AUTH-TOKEN") &&
                        LoginManager.get().getToken() != null) {
                    builder.addHeader("X-AUTH-TOKEN", LoginManager.get().getToken());
                }

                newRequest = builder.build();

            }
        } catch (Exception e) {
            e.printStackTrace();
            UploadManager.uploadException(e, "FirebaseHeaderInterceptor.intercept");
        }

        return chain.proceed(newRequest);
    }

    private static boolean existHeader(Headers headers, String header) {
        if (headers == null || headers.names() == null || header == null || headers.size() == 0 || header.length() == 0) {
            return false;
        }

        return headers.names().contains(header);
    }

    private static String install_referrer_uploaded_key = "install_referrer_uploaded_key";
    private static String install_referrer_uploaded_with_token_key = "install_referrer_uploaded_with_token_key";


}
