package tech.starwin.network;


import android.text.TextUtils;

import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.Util;
import tech.starwin.LibConfig;
import tech.starwin.utils.LoginManager;
import tech.starwin.utils.context_utils.AppInfoUtils;

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

class DefaultHeaderAddInterceptor implements Interceptor {
    public static String GA_ID = "";
    public static String SIM_INFO = "";
    public static String ROOT_STATUS = "";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request userRequest = chain.request();
        Request.Builder requestBuilder = userRequest.newBuilder();
        RequestBody body = userRequest.body();
        if (body != null) {
            MediaType contentType = body.contentType();
            if (contentType != null) {
                requestBuilder.header("Content-Type", contentType.toString());
            }

            long contentLength = body.contentLength();
            if (contentLength != -1L) {
                requestBuilder.header("Content-Length", Long.toString(contentLength));
                requestBuilder.removeHeader("Transfer-Encoding");
            } else {
                requestBuilder.header("Transfer-Encoding", "chunked");
                requestBuilder.removeHeader("Content-Length");
            }
        }

        if (userRequest.header("Host") == null) {
            requestBuilder.header("Host", Util.hostHeader(userRequest.url(), false));
        }

        if (userRequest.header("Connection") == null) {
            requestBuilder.header("Connection", "Keep-Alive");
        }

        if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
            requestBuilder.header("Accept-Encoding", "gzip");
        }

        requestBuilder.header("X-APP-TYPE", "ANDROID")
                .header("X-APP-VERSION", String.valueOf(LibConfig.VERSION_CODE))
                .header("X-APP-VERSION-NAME", String.valueOf(LibConfig.VERSION_NAME))
                .header("X-APP-PACKAGE-NAME", LibConfig.APPLICATION_ID)
                .header("X-APP-NAME", LibConfig.APP_NAME)
                .header("X-APP-ROOTED", getRootStatus())
                .header("X-AUTH-TOKEN", LoginManager.get().getToken() == null ? "" : LoginManager.get().getToken())
                .header("X-APP-SOURCE", LibConfig.XH_CHANNEL_NAME == null ? "" : LibConfig.XH_CHANNEL_NAME)
                .header("thirdpartyDataFlag", String.valueOf(!TextUtils.isEmpty(LibConfig.TONGDUN_PARENT_KEY)))
//                .header("X-APP-SIM-MOBILE", getSimInfo())
                .header("X-AF-ID", LibConfig.APPSFLYER_DEV_KEY == null ? "" : LibConfig.APPSFLYER_DEV_KEY)
                .header("X-GA-ID", getGAId());

        return chain.proceed(requestBuilder.build());
    }

    public String getRootStatus() {
        if (TextUtils.isEmpty(ROOT_STATUS)) {
            ROOT_STATUS = String.valueOf(AppInfoUtils.isRoot());
        }
        return ROOT_STATUS;
    }

//    public String getSimInfo() {
//        if (TextUtils.isEmpty(SIM_INFO)) {
//            String sim_info = AppInfoUtils.getSimSerialNumber(LibConfig.getContext()) + "," + AppInfoUtils.getPhoneNumber(LibConfig.getContext());
//            if (sim_info.length() > 1) {
//                SIM_INFO = sim_info;
//            }
//        }
//        return SIM_INFO;
//    }

    private String getGAId() {
        if (!TextUtils.isEmpty(GA_ID)) {
            return GA_ID;
        }
        AdvertisingIdClient.Info adInfo = null;
        try {
            adInfo = AdvertisingIdClient.getAdvertisingIdInfo(LibConfig.getContext());
            GA_ID = adInfo.getId();
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        } catch (GooglePlayServicesRepairableException e) {
            e.printStackTrace();
        }
        return GA_ID;
    }


}
