package com.qimai.android.fetch.interceptors

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

/**
 * @author wangwei

 * @version 1.1.1
 * @date 2019-08-14
 * @Description
 * @email wangwei_5521@163.com
 **/
abstract class HeaderInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val headers = buildHeaders()
        return if (headers.isEmpty()) {
            chain.proceed(request)
        } else {
            chain.proceed(
                request.newBuilder()
                    .headers(addHeaders(request, headers))
                    .build()
            )
        }
    }

    private fun addHeaders(request: Request, headerMap: Map<String, String>): Headers {
        val headers = request.headers()
        val builder = headers.newBuilder()
        for (key in headerMap.keys) {
            builder.add(key, headerMap[key])
        }
        return builder.build()
    }

    abstract fun buildHeaders(): Map<String, String>
}