package com.gingersoft.gsa.cloud.config.globalconfig.applyOptions.intercept;

import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.BuildConfig;
import com.gingersoft.gsa.cloud.base.utils.encryption.Aes;
import com.gingersoft.gsa.cloud.constans.AppConstans;
import com.jess.arms.utils.DeviceUtils;

import java.io.IOException;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 添加請求頭信息
 */
public class HeadersInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();

        Headers.Builder builder = new Headers.Builder();
        builder.set("mobileVersion", android.os.Build.VERSION.RELEASE);
        builder.set("mobielModel", android.os.Build.MODEL);
        builder.set("apptype", AppConstans.APP_TYPE);
        builder.set("appinfo", DeviceUtils.getVersionName(GsaCloudApplication.getAppContext()));
        builder.set("mobileId", "1");
        builder.set("uid", GsaCloudApplication.getMemberId() + "");
        Headers headers = originalRequest.headers();
        for (int i = 0; i < headers.size(); i++) {
            builder.set(headers.name(i), headers.value(i));
        }
        if (GsaCloudApplication.isLogin) {
            builder.set("token", getToken());
        } else if (BuildConfig.DEBUG) {
            builder.set("uuid", "999");
            builder.set("uid", "397");
        }
        Request requestWithUserAgent = originalRequest.newBuilder()
                .headers(builder.build())
                .build();
        return chain.proceed(requestWithUserAgent);
    }

    private String getToken() {
        String token = "";
        if (GsaCloudApplication.isLogin) {
            int memberId = GsaCloudApplication.getMemberId();
            String loginToken = GsaCloudApplication.getLoginToken();
            token = Aes.aesEncrypt("9_" + memberId + "_" + System.currentTimeMillis() + "_" + loginToken);
            token = token.replaceAll("\r|\n", "");
        }
        return token;
    }
}