package tech.starwin.network;


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

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.RequestHandler;
import tech.starwin.utils.context_utils.AppInfoUtils;
import tech.starwin.utils.context_utils.DeviceUtils;

/**
 * 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()));

                if (PreferencesManager.get().getCustomerInfo() != null) {
                    String secretKey = PreferencesManager.get().getCustomerInfo().getRestUrlSignKey();
                    //header签名
                    new RequestHandler.Builder(secretKey)
                            .headerDeviceSign(DeviceUtils.getInstance().getSignFromHardware())
                            .headerSDSign("")
                            .bindHttpBuilder(request, builder)
                            .build().signHeaders();
                }

                request = builder.build();

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


}
