package com.wdkl.ncs.android.middleware.logic.presenter.callingbed

import android.util.Log
import com.enation.javashop.net.engine.plugin.connection.ConnectionQuality
import com.enation.javashop.net.engine.plugin.exception.ExceptionHandle
import com.enation.javashop.net.engine.utils.ThreadFromUtils
import com.google.gson.FieldNamingPolicy
import com.google.gson.GsonBuilder
import com.wdkl.ncs.android.lib.base.RxPresenter
import com.wdkl.ncs.android.lib.utils.*
import com.wdkl.ncs.android.middleware.api.CallingbedApi
import com.wdkl.ncs.android.middleware.api.ExtraApi
import com.wdkl.ncs.android.middleware.api.PromotionApi
import com.wdkl.ncs.android.middleware.di.MiddlewareDaggerComponent
import com.wdkl.ncs.android.middleware.logic.contract.callingbed.MainFragmentContract
import com.wdkl.ncs.android.middleware.model.*
import com.wdkl.ncs.android.middleware.model.vo.CustomerInfoVO
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import org.json.JSONArray
import org.json.JSONObject
import javax.inject.Inject

class MainFragmentPresenter @Inject constructor() : RxPresenter<MainFragmentContract.View>(), MainFragmentContract.Presenter  {

    @Inject
    protected lateinit var bedDeviceApi : CallingbedApi

    /**
     * @Name  observer
     * @Type  ConnectionObserver
     * @Note  数据监听者
     */
    private val observer = object : ConnectionObserver<Any>() {
        override fun onStartWithConnection() {
            providerView().start()
        }

        override fun onNextWithConnection(result: Any, connectionQuality: ConnectionQuality) {
            providerView().complete("")
            providerView().showCustomInfo(result as CustomerInfoVO)
        }

        override fun onErrorWithConnection(error: ExceptionHandle.ResponeThrowable, connectionQuality: ConnectionQuality) {
            providerView().onError(error.customMessage)
        }

        override fun attachSubscribe(var1: Disposable) {
            addDisposable(var1)
        }

        override fun onNoneNet() {
            Log.d("MainFragmentPresenter", "onNoneNet...")
            super.onNoneNet()
            providerView().onNoNet()
        }
    }


    override fun bindDagger() {
        MiddlewareDaggerComponent.component.inject(this)
    }

    override fun loadCustomInfo(customId: Int) {
        bedDeviceApi.getCustomInfo(customId)
                .map {
                    val gson = GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
                    val customerInfoVO = gson.fromJson(it.getJsonString(), CustomerInfoVO::class.java)

                    return@map customerInfoVO
                }
                .compose(ThreadFromUtils.defaultSchedulers())
                .subscribe(observer)
    }
}