package com.za.net

import com.za.base.AppConfig
import com.za.common.log.LogUtil
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
import java.util.concurrent.TimeUnit

object RetrofitHelper {
	private var retrofit : Retrofit? = null
	private var apiService : ApiService? = null
	private val loggerInterceptor = HttpLoggingInterceptor {
		try {

			if (it.contains("image/*") || it.contains("form-data; name=\"file\"") || it.startsWith("Content-Type") || it.startsWith(
					"Content-Length") || it.startsWith("Server") || it.startsWith("Date") || it.startsWith(
					"Transfer-Encoding") || it.startsWith("Connection") || it.startsWith("X-") || it.startsWith(
					"token") || it.startsWith("Cache-Control") || it.startsWith("Expires") || it.startsWith(
					"Accept") || it.startsWith("Vary") || it.isEmpty() || it.startsWith("Pragma")
			) {
				return@HttpLoggingInterceptor
			}

			if (it.contains("name=\"file\"; filename")) {
				return@HttpLoggingInterceptor
			}
			LogUtil.print("--network--",
				URLDecoder.decode(it.replace(Regex("%(?![0-9a-fA-F]{2})"), ""), "utf-8"))
		} catch (e : UnsupportedEncodingException) {
			e.printStackTrace()
		}

	}.setLevel(HttpLoggingInterceptor.Level.BODY)

	fun reset() {
		apiService = null
		retrofit = null
	}

	fun getDefaultService() : ApiService {
		return if (apiService == null) {
			apiService = getDefaultRetrofit().create(ApiService::class.java)
			apiService !!
		} else {
			apiService !!
		}
	}

	private fun getDefaultRetrofit() : Retrofit {
		return if (retrofit == null) {
			retrofit = Retrofit.Builder().baseUrl(AppConfig.BASE_URL)
				.addConverterFactory(GsonConverterFactory.create())
				.addCallAdapterFactory(RxJava3CallAdapterFactory.create()).client(getOkHttpClient())
				.build()
			retrofit !!
		} else {
			retrofit !!
		}
	}

	private fun getOkHttpClient() : OkHttpClient {
		return OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS)
			.writeTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS)
			.addInterceptor(RequestEncryptInterceptor()).addInterceptor(loggerInterceptor).build()
	}
}