package com.fastcashier.lib_common.net

import android.util.Log
import com.blankj.utilcode.util.LogUtils
import com.fastcashier.lib_common.base.BaseApplication
import com.fastcashier.lib_common.util.LogFileUtils
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.X509TrustManager


class ApiClient private constructor() {

    companion object {

        private var sInstance: ApiClient? = null

        @Synchronized
        fun getInstance(): ApiClient {
            if (null == sInstance) {
                sInstance = ApiClient()
            }
            return sInstance!!
        }
    }

    private fun generateClient(): Retrofit {
        val httpLoggingInterceptor =
            MiyaHttpLoggingInterceptor {
                Log.e("####", it)
                if (!LogFileUtils.isProhibitWrite) {
                    LogFileUtils.writeLog(BaseApplication.getApplication(), it)
                }
            }.apply { level = MiyaHttpLoggingInterceptor.Level.BODY }


        val socketFactory = arrayOfNulls<SSLSocketFactory>(1)
        val trustManager = arrayOfNulls<X509TrustManager>(1)
        SSLCertificatesInit.init(socketFactory, trustManager)

        val client = OkHttpClient.Builder()
            .addInterceptor(httpLoggingInterceptor)
            .addInterceptor(RequestSignInterceptor())
            .sslSocketFactory(socketFactory[0]!!, trustManager[0]!!)
            .build()

        val retrofit = Retrofit.Builder()
            .baseUrl(ApiConfig.baseUrl)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        return retrofit
    }

    fun <T> creatApi(tClass: Class<T>?): T? {
        return generateClient().create(tClass)
    }
}