package tech.starwin.network;


import android.os.Build;
import android.text.TextUtils;

import com.common.toolbox.app_utils.DeviceInfo;
import com.common.toolbox.app_utils.RequestHandler;
import com.facebook.libfbref.FbDeepLink;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.FormBody;
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.PreferencesManager;
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 request = chain.request();

        try {
            if (request != null) {
                Request.Builder builder = chain.request().newBuilder();

                String referrer = FbDeepLink.getFbReferrer();
                builder.addHeader("X-REFERRER", TextUtils.isEmpty(referrer) ? PreferencesManager.get().getInstallReferrer() : referrer)
                        .addHeader("X-REFERRER-SDK", TextUtils.isEmpty(referrer) ? PreferencesManager.get().getInstallReferrerFromSDK() : referrer)
                        .addHeader("X-ANDROID-ID", AppInfoUtils.getAndroidID(LibConfig.getContext()));

                String secretKey = PreferencesManager.get().getCustomerInfo().getRestUrlSignKey();

                //header签名
                new RequestHandler.Builder(secretKey)
                        .headerDeviceSign(DeviceInfo.getSignFromHardware())
                        .headerSDSign(DeviceInfo.getDeviceSignFromSD())
                        .bindHttpBuilder(request,builder)
                        .build().signHeaders();

                request = builder.build();

                LogUtils.d("HttpHeaders", request.headers().toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            //UploadManager.uploadException(e, "FirebaseHeaderInterceptor.intercept");
        }

        return chain.proceed(request);
    }

    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";


}
