package com.mogo.v2x.http

import com.elegant.network.utils.GsonUtil
import com.elegant.network.utils.SignUtil
import com.elegant.utils.CommonUtils
import com.mogo.cloud.network.RetrofitFactory
import com.mogo.v2x.V2XManager
import com.mogo.v2x.config.V2XConfig
import com.mogo.v2x.data.V2XLocation
import com.mogo.v2x.data.V2XMarkerResponse
import com.mogo.v2x.http.api.V2XApiService
import com.mogo.v2x.http.body.V2XRefreshEntity
import com.mogo.v2x.http.callback.IV2XRefreshCallback
import com.mogo.v2x.utils.DeviceUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.atomic.AtomicReference

internal class V2XRefreshModel {

    companion object {

        fun querySnapshot(
            longitude: Double,
            latitude: Double,
            callback: IV2XRefreshCallback<V2XMarkerResponse>?
        ): Disposable? {
            val config = V2XManager.getConfig()
            val retrofit = RetrofitFactory.getInstance(config.baseUrl) ?: return null
            return retrofit
                .create(V2XApiService::class.java)
                .querySnapshotSync(buildParams(longitude, latitude, config))
                .subscribeOn(Schedulers.from(config.executor))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ data ->
                    if (data == null) {
                        callback?.onFail("returned data is null.")
                        return@subscribe
                    }
                    if (data.code != 0 && data.code != 200) {
                        callback?.onFail("code:${data.code}, msg: ${data.msg}")
                    } else {
                        callback?.onSuccess(data)
                    }
                }, {
                    callback?.onFail(it.message)
                })
        }

        private fun buildParams(
            longitude: Double,
            latitude: Double,
            config: V2XConfig
        ): Map<String, Any> = mutableMapOf<String, Any>().apply {
            putAll(config.staticParams.let {
                val handled = mutableMapOf<String, Any>()
                it.asIterable().forEach { itx ->
                    val value = itx.value
                    if (value != null) {
                        handled[itx.key] = value
                    }
                }
                handled
            })
            this["netType"] = CommonUtils.getNetworkType(config.context)
            this["cellId"] = DeviceUtils.getCellId(config.context) ?: ""
            this["sn"] = config.aiCloudConfig.sn
            this["ticket"] = config.aiCloudConfig.token
            this["sig"] = SignUtil.createSign(this, "JGjZx6")
            this["data"] = GsonUtil.jsonFromObject(V2XRefreshEntity().apply {
                limit = 999
                location = V2XLocation().also {
                    it.lat = latitude
                    it.lon = longitude
                }
                radius = 1000
                dataType.add("CARD_TYPE_ROAD_CONDITION")
                viewPush = true
            })
        }
    }


}
