package com.qimai.android.fetch

import android.text.TextUtils
import android.util.Log
import com.google.gson.Gson
import com.qimai.android.fetch.adapter.LiveDataCallAdapterFactory
import com.qimai.android.fetch.config.HeaderConfig
import com.qimai.android.fetch.config.OkHttpConfig
import com.qimai.android.fetch.convert.StandardGsonConvertFactory
import com.qimai.android.fetch.gson.GsonAdapter
import com.qimai.android.fetch.interceptors.MultiHostInterceptor
import com.qimai.android.fetch.interceptors.TokenExpire
import com.qimai.android.fetch.retrofit.RetrofitBuilder
import com.qimai.android.tools.SharedPreferencesTools
import okhttp3.logging.HttpLoggingInterceptor
import org.greenrobot.eventbus.EventBus
import retrofit2.CallAdapter
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory

/**
 * @author wangwei

 * @version 1.1.1
 * @date 2019-08-13
 * @Description
 * @email wangwei_5521@163.com
 **/
class FetchWebApi private constructor() {
    private var retrofit: Retrofit
    private var gson = Gson()

    private fun getMultistoreId(): String {
        val infoString = SharedPreferencesTools.instance.getString("AccountInfo", "")
        return if (TextUtils.isEmpty(infoString)) {
            ""
        } else {
            gson
                .fromJson(infoString, AccountInfo::class.java).shopId
        }
    }

    init {
        val okHttpClient = OkHttpConfig.Builder()
            .connectTimeOut(20)
            .readTimeOut(20)
            .writeTimeOut(20)
            .debug(BuildConfig.DEBUG)
            .intercepteors( MultiHostInterceptor(AppUrlConfig.getUrlMap()),HttpLoggingInterceptor { message ->
                Log.d(
                    "fetch",
                    message
                )
            }.setLevel(HttpLoggingInterceptor.Level.HEADERS))
            .headers(object : HeaderConfig {
                override fun buildHeaders(): Map<String, String> {
                    val header = mutableMapOf<String, String>()
                    header["Accept"] = "*/*; v=1.0"
                    header["Referer"] = BuildConfig.WEB_URL
                    header["QM-FROM"] = "android"
                    header["multi_store_id"] = getMultistoreId()

                    header["Qm-Account-Token"] =
                        SharedPreferencesTools.instance.getString("TOKEN", "") ?: ""
                    header["User-Agent"] = "wechatdevtools appservice port/62739"
                    header["Qm-From-Type"] = "cy"
                    header["request-source"] = "canyin"
                    header["Authorization"] =
                        "Authorization Bearer ${SharedPreferencesTools.instance.getString(
                            "TOKEN",
                            ""
                        )
                            ?: ""}"
                    return header
                }
            })
            .build().okHttpClient()

        val callAdapters = mutableListOf<CallAdapter.Factory>()
        val convertFactories = mutableListOf<Converter.Factory>()

        convertFactories.add(
            StandardGsonConvertFactory(
                GsonAdapter.buildGson(),
                object : TokenExpire {
                    override fun expre() {
                        EventBus.getDefault().post(TokenExpireEvent())
                    }
                })
        )
        convertFactories.add(ScalarsConverterFactory.create())
        callAdapters.add(LiveDataCallAdapterFactory())

        retrofit = RetrofitBuilder.Builder()
            .convertFactory(convertFactories)
            .baseUrl(BuildConfig.WEB_URL)
            .callAdapterFactory(callAdapters)
            .okhttpClient(okHttpClient)
            .build()

    }

    companion object {
        val instance: FetchWebApi by lazy {
            FetchWebApi()
        }
    }

    fun <T> createApi(clz: Class<T>): T {
        return retrofit.create(clz)
    }


}