package com.common.commonlib.net.interceptor

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

/**
 * 公共请求拦截器
 *
 * @author wangym
 * @since 2021/7/28
 */
class RequestHeadInterceptor : Interceptor {
    /**
     * 请求头部参数
     */
    var mHeaderHashMap: HashMap<String, String> = HashMap()

    /**
     * 拦截请求并添加参数
     */
    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest: Request = chain.request()
        val requestBuilder: Request.Builder = oldRequest.newBuilder()
        requestBuilder.method(oldRequest.method, oldRequest.body)
        if (mHeaderHashMap.size > 0) {
            for (item: Map.Entry<String, String> in mHeaderHashMap.entries) {
                requestBuilder.addHeader(item.key, item.value)
            }
        }
        return chain.proceed(requestBuilder.build())
    }

    /**
     * builder构造函数
     */
    class Builder {
        private var mHttpCommonInterceptor: RequestHeadInterceptor? = null

        init {
            mHttpCommonInterceptor = RequestHeadInterceptor()
        }

        fun addHeadParams(key: String, value: String): Builder {
            mHttpCommonInterceptor?.mHeaderHashMap?.set(key, value)
            return this
        }

        fun addHeadParams(key: String, value: Int): Builder {
            mHttpCommonInterceptor?.mHeaderHashMap?.set(key, value.toString())
            return this
        }

        fun addHeadParams(key: String, value: Long): Builder {
            mHttpCommonInterceptor?.mHeaderHashMap?.set(key, value.toString())
            return this
        }

        fun addHeadParams(key: String, value: Float): Builder {
            mHttpCommonInterceptor?.mHeaderHashMap?.set(key, value.toString())
            return this
        }

        fun addHeadParams(key: String, value: Double): Builder {
            mHttpCommonInterceptor?.mHeaderHashMap?.set(key, value.toString())
            return this
        }

        fun build(): RequestHeadInterceptor {
            return mHttpCommonInterceptor!!
        }
    }
}