package com.fastcashier.lib_common.net

import android.util.Log
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 NetClient private constructor() {

    companion object {

//        private var apiService: BaseApi? = null
        private var sInstance: NetClient? = null

        @Synchronized
        fun getInstance(): NetClient {
            if (null == sInstance) {
                sInstance = NetClient()
            }
            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> getApi(tClass: Class<T>?): T {
//        if (null == apiService) {
//            apiService = generateClient().create(tClass)
//        }
//
//        return apiService!!
//    }

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