package com.swago.baseswago.http

import android.util.Log
import com.swago.baseswago.util.LogUtil
import com.swago.baseswago.util.MD5Util
import com.swago.baseswago.util.SwagoInfo
import com.swago.baseswago.util.UserInfo.getLoginModel
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.util.*

/**
 * @date 2021/8/14 14:10
 * description:
 */
class SwagoInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        val time = System.currentTimeMillis()/1000

        val stringBuffer = StringBuffer()
        request.url.pathSegments.forEach {
            stringBuffer.append("${it}/")
        }
        val appUrl = stringBuffer.substring(0,stringBuffer.length-1)
        stringBuffer.delete(0,stringBuffer.length)
        stringBuffer.append("app-client:${SwagoInfo.getAppClient()}")
            .append(":")
            .append("app-client-version:${SwagoInfo.getVersionCode()}")
            .append(":")
            .append("app-client-device:${SwagoInfo.getDeviceInfo()}")
            .append(":")
            .append("app-client-channel:${SwagoInfo.getChannel()}")
            .append(":")
            .append("app-time:${time}")
            .append(":")
            .append("app-url:${appUrl}")

        LogUtil.d("加密路径", appUrl)
        LogUtil.d("加密前", "$stringBuffer")
        val secret = MD5Util.md5Hex(stringBuffer.toString()).uppercase()
        LogUtil.d("加密后", secret)

        val finalRequest = chain.request().newBuilder()
            .addHeader("apiToken", getLoginModel()?.token ?: "")
            .addHeader("languageCode", SwagoInfo.getLanguageCode())
            .addHeader("app-client-version", SwagoInfo.getVersionCode())
            .addHeader("app-client", SwagoInfo.getAppClient())
            .addHeader("app-client-device", SwagoInfo.getDeviceInfo())
            .addHeader("app-client-channel", SwagoInfo.getChannel())
            .addHeader("app-time", "$time")
            .addHeader("app-secret", secret)
            .addHeader("app-client-device-id",SwagoInfo.getIMEI())
            .build()
        return chain.proceed(finalRequest)
    }
}