package com.qimai.android.fetch.interceptors

import android.text.TextUtils
import android.util.Log
import com.qimai.android.fetch.HOST_KEY
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

/**
 * @author wangwei

 * @version 1.1.1
 * @date 2019-08-12
 * @Description 动态切换Host
 * @email wangwei_5521@163.com
 **/
class MultiHostInterceptor(var urlMap: MutableMap<String, HttpUrl>) : Interceptor {

    // key : hostname
    private val httpURLCache = mutableMapOf<String, HttpUrl>()

    override fun intercept(chain: Interceptor.Chain): Response {

        val originRequest = chain.request()
        try{
            return  chain.proceed(processRequest(originRequest))
        }catch(e: IOException){
            Log.d("MultiHostInterceptor", "intercept: e= $e")
            throw e
        }

    }


    private fun processRequest(request: Request): Request {

        val newBuilder = request.newBuilder()
        val headers = request.headers(HOST_KEY)
        val domainName = when {
            headers.size == 0 -> null
            headers.size > 1 -> {
                throw Throwable("header 只允许设置一个domain-name")
            }
            else -> request.header(HOST_KEY)
        }
        var httpUrl: HttpUrl?
        if (!TextUtils.isEmpty(domainName)) {
            httpUrl = httpURLCache[domainName]
            newBuilder.removeHeader(HOST_KEY)
            if (httpUrl == null) {
                var baseUrl = urlMap["$domainName"]!!
                httpUrl = request.url().newBuilder()
                    .host(baseUrl.host())
                    .scheme(baseUrl.scheme())
                    .port(baseUrl.port())
                    .build()
                httpURLCache["$domainName"] = httpUrl
            }
            return newBuilder.url(httpUrl).build()

        }
        return request
    }
}