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

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.Gson
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.ShopApi
import com.wdkl.ncs.android.middleware.di.MiddlewareDaggerComponent
import com.wdkl.ncs.android.middleware.logic.contract.hello.HelloListActivityContract
import com.wdkl.ncs.android.middleware.model.JavaShopItem
import com.wdkl.ncs.android.middleware.model.ShopItem
import io.reactivex.disposables.Disposable
import javax.inject.Inject

class HelloListActivityPresenter @Inject constructor(): RxPresenter<HelloListActivityContract.View>(),HelloListActivityContract.Presenter{
    override fun bindDagger() {
        MiddlewareDaggerComponent.component.inject(this)
    }
    @Inject
    protected lateinit var shopApi: ShopApi

    private val observer = object : ConnectionObserver<Any>(){
        override fun onStartWithConnection() {
            providerView().start()
        }

        override fun onNextWithConnection(result: Any, connectionQuality: ConnectionQuality) {
            providerView().complete("")
            providerView().render(result as ArrayList<JavaShopItem>)
        }

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

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

    override fun loadData(keyWord: String, page: Int) {
        shopApi.getShopList(page,10,keyWord)
                .map {
                    var shop = ArrayList<JavaShopItem>()
                    var gson = GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
                    it.toJsonObject().valueJsonArray("data").arrayObjects().forEach({ dic ->
                        shop.add(gson.fromJson(dic.toString(),JavaShopItem::class.java))
                    })
                    return@map shop
                }
                .compose(ThreadFromUtils.defaultSchedulers())
                .subscribe(observer)
    }
}