package com.swago.baseswago.http

import android.text.TextUtils
import android.util.Log
import com.swago.baseswago.constant.UrlConstant
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Response

class UrlChangeInterceptor : Interceptor {

    private var baseURL: HttpUrl? = null

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val headerValue = request.header("urlFlag")
        if (!TextUtils.isEmpty(headerValue)){
            baseURL = when(headerValue){
                "apiDomain" -> {
                    "http://doc.swago.cn".toHttpUrlOrNull()
                }

                else -> {
                    UrlConstant.BASE_URL.toHttpUrlOrNull()
                }
            }

            val newBuilder = request.newBuilder()
            newBuilder.removeHeader("urlFlag")
            baseURL?.let {
                val newHttpUrl = request.url.newBuilder()
                    .scheme(it.scheme)
                    .host(it.host)
                    .port(it.port)
                    .build()
                Log.i("zkc","转换的：${it.host}   ${it.port}")

                val newRequest = newBuilder.url(newHttpUrl).build()
                return chain.proceed(newRequest)
            }

        }else{
            return chain.proceed(request)
        }

        return chain.proceed(request)
    }
}