package com.miya.fastcashier.net

import android.util.Log
import com.miya.fastcashier.BaseApplication
import com.miya.fastcashier.beans.SelfCashierAccountInfo
import com.miya.fastcashier.beans.LoginRequest;
import com.miya.fastcashier.utils.LogFileUtils
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.X509TrustManager


class ApiRequest private constructor() {

    companion object {

        private var apiService: ApiService? = null
        private var sInstance: ApiRequest? = null

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

        private fun getApiService(): ApiService {
            if (null == apiService) {
                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()

                apiService = retrofit.create(ApiService::class.java)
            }

            return apiService!!
        }
    }

    fun login(
        loginRequest: LoginRequest,
        commonCallback: CommonCallback<SelfCashierAccountInfo>
    ) {
        getApiService().login(loginRequest).enqueue(commonCallback)
    }

    fun uploadFile(
        url: String,
        part: MultipartBody.Part,
        commonCallback: CommonCallback<String>
    ) {
        getApiService().uploadFile(url, part).enqueue(commonCallback)
    }
}