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

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.google.gson.reflect.TypeToken
import com.wdkl.ncs.android.lib.base.RxPresenter
import com.wdkl.ncs.android.lib.utils.ConnectionObserver
import com.wdkl.ncs.android.lib.utils.getJsonString
import com.wdkl.ncs.android.middleware.api.CallingbedApi
import com.wdkl.ncs.android.middleware.di.MiddlewareDaggerComponent
import com.wdkl.ncs.android.middleware.logic.contract.callingbed.CostFragmentContract
import com.wdkl.ncs.android.middleware.model.vo.CustomerFeeConfigByGroupNameVO
import io.reactivex.disposables.Disposable
import javax.inject.Inject

class CostFragmentPresenter @Inject constructor() : RxPresenter<CostFragmentContract.View>(), CostFragmentContract.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().showCustomCost(result as ArrayList<CustomerFeeConfigByGroupNameVO>)
        }

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

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


        override fun onNoneNet() {
            super.onNoneNet()
            providerView().onNoNet()
        }
    }


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

    override fun loadCustomCost(customId: Int) {
        bedDeviceApi.getCustomCost(customId)
                .map {
                    val data = it.getJsonString()
                    val gson = GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
                    val itemType = object : TypeToken<ArrayList<CustomerFeeConfigByGroupNameVO>>(){}.type
                    val customCostVO = gson.fromJson<ArrayList<CustomerFeeConfigByGroupNameVO>>(data, itemType)

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