package com.za.common.log

import android.util.Log
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 LogRetrofitHelper {
    private var retrofit: Retrofit? = null
    private var apiService: LogService? = null
    private val loggerInterceptor = HttpLoggingInterceptor {
        try {
            if (it.contains("image/*")) {
                return@HttpLoggingInterceptor
            }
            if (it.contains("name=\"file\"; filename")) {
                return@HttpLoggingInterceptor
            }
            Log.e(
                "--network--",
                URLDecoder.decode(it.replace(Regex("%(?![0-9a-fA-F]{2})"), ""), "utf-8")
            )
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }

    }.setLevel(HttpLoggingInterceptor.Level.BODY)


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

    private fun getDefaultRetrofit(): Retrofit {
        return if (retrofit == null) {
            retrofit = Retrofit.Builder().baseUrl("https://api2.sino-assist.com")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .client(getOkHttpClient())
                .build()
            retrofit!!
        } else {
            retrofit!!
        }
    }

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