package com.miya.fastcashier.net

import android.util.Log
import com.miya.fastcashier.beans.SelfCashierAccountInfo
import com.miya.fastcashier.beans.LoginRequest;
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory


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)
                    }.apply { level = MiyaHttpLoggingInterceptor.Level.BODY }

                val client = OkHttpClient.Builder()
                    .addInterceptor(httpLoggingInterceptor)
                    .addInterceptor(RequestSignInterceptor())
                    .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)
    }
}