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

import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.common.BuildConfig;
import com.gingersoft.gsa.cloud.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.oaId.DeviceID;
import com.gingersoft.gsa.cloud.common.utils.encryption.Aes;
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", UserContext.newInstance().getMemberId() + "");
        builder.set("deviceId", DeviceID.getDeviceId());

        Headers headers = originalRequest.headers();
        for (int i = 0; i < headers.size(); i++) {
            builder.set(headers.name(i), headers.value(i));
        }
        if (UserContext.newInstance().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 (UserContext.newInstance().isLogin()) {
            int memberId = UserContext.newInstance().getMemberId();
            String loginToken = UserContext.newInstance().getLoginToken();
            token = Aes.aesEncrypt("9_" + memberId + "_" + System.currentTimeMillis() + "_" + loginToken);
            token = token.replaceAll("\r|\n", "");
        }
        return token;
    }
}