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.GeneralUtils;
import tech.starwin.utils.LoginManager;
import tech.starwin.utils.PreferencesManager;
import tech.starwin.utils.collection.UploadManager;

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

public class FirebaseHeaderInterceptor implements Interceptor {

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

        Request newRequest = chain.request();

        try {
            if (newRequest != null) {

                Request.Builder builder = chain.request().newBuilder();

                builder.addHeader("X-REFERRER", PreferencesManager.get().getInstallReferrer())
//                        .addHeader("X-REFERRER-SDK", FirebaseAnalytics.getInstance(LibConfig.getContext()).)
                        .addHeader("X-ANDROID-ID", GeneralUtils.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";


}
