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.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.lib.utils.more
import com.wdkl.ncs.android.middleware.api.HelloApi
import com.wdkl.ncs.android.middleware.di.MiddlewareDaggerComponent
import com.wdkl.ncs.android.middleware.logic.contract.hello.HelloActivityContract
import com.wdkl.ncs.android.middleware.model.ChildCategoryShell
import io.reactivex.disposables.Disposable
import org.json.JSONArray
import javax.inject.Inject

class HelloActivityPresenter @Inject constructor() :RxPresenter<HelloActivityContract.View>(),HelloActivityContract.Presenter{
    override fun bindDagger() {
        MiddlewareDaggerComponent.component.inject(this)
    }

    @Inject
    protected lateinit var helloApi: HelloApi

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

        override fun onNextWithConnection(result: ArrayList<*>, connectionQuality: ConnectionQuality) {
            providerView().complete()
            result.getOrNull(0)?.more { data ->
                providerView().showData(result as ArrayList<ChildCategoryShell>)
            }
        }

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

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

    override fun loadData(parentId: Int) {
        helloApi.getCategories(parentId).map { response->
            var jsonResult = response.getJsonString()
            /**初始化Result数据*/
            val result = ArrayList<Any>()

            if (jsonResult != ""){
                val jsonArray = JSONArray(jsonResult)
                for (i in 0..(jsonArray.length() - 1)){
                    val item = ChildCategoryShell.map(jsonArray.getJSONObject(i))
                    result.add(item)
                }
            }

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