package com.ydl.confide.home.presenter

import android.content.Context
import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ydl.confide.home.bean.ConfideHomeDataBean
import com.ydl.confide.home.contract.IConfideHomeContract
import com.ydl.confide.home.http.ConfideRecommendParam
import com.ydl.confide.home.model.ConfideHomeModelImpl
import com.ydl.confide.home.util.ConfideHomeUtils
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.mvp.base.BasePresenter
import com.ydl.ydlcommon.mvp.base.IView
import com.ydl.ydlcommon.utils.YDLAsyncUtils
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.yidianling.common.tools.RxNetTool
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer

/**
 * @author yuanwai
 * @描述:倾诉首页逻辑实现类
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/8/10
 */
class ConfideHomePresenterImpl : BasePresenter<IConfideHomeContract.View,IConfideHomeContract.Model>(), IConfideHomeContract.Presenter{

    override fun createModel(): IConfideHomeContract.Model {
        return ConfideHomeModelImpl()
    }

    /**
     * 加载本地缓存
     */
    override fun loadLocalData(context: Context) {
        YDLAsyncUtils.asyncAsResult(object : YDLAsyncUtils.AsyncObjecyerResult{
            override fun doAsyncAction(): Any {

                //读取缓存数据
                var cacheData = YDLCacheUtils.getConfideHomeData()

                if (cacheData.isEmpty()) {
                    cacheData = String(ConfideHomeUtils.getAssertsFile(context, "confide_home.json")!!)
                }

                return cacheData
        }

            override fun asyncResult(`object`: Any?) {
                //如果没有缓存数据，显示加载框
                if (`object` !is String || TextUtils.isEmpty(`object`)){
                    mView.showLoading()
                }

                if (`object` is String){
                    val gson = Gson()
                    val list = gson.fromJson<MutableList<ConfideHomeDataBean>>(`object`, object : TypeToken<MutableList<ConfideHomeDataBean>>() {

                    }.type)
                    if(null != list && !list.isEmpty()){
                        mView.confideHomeResponse(list)
                    }
                }
                confideHomeRequest(false)
            }
        })
    }

    /**
     * 请求首页数据
     */
    override fun confideHomeRequest(isRefresh:Boolean) {
        if (!RxNetTool.isConnected(mView.getContext())){
            mView.confideHomeRequestFail()
            return
        }
        val disposable = mModel.confideHomeRequest()
                .map { it }
                .filter { it != null }
                .compose(RxUtils.applySchedulers(mView as IView))
                .doFinally { mView.hideLoading() }
                .subscribe(Consumer {
                    mView.confideHomeResponse(it)
                    updateCache(it)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        mView.confideHomeRequestFail()
                    }
                })
    }

    /**
     * 更新本地缓存
     */
    private fun updateCache(list : MutableList<ConfideHomeDataBean>){
        YDLAsyncUtils.async(object : YDLAsyncUtils.AsyncObjecyer{
            override fun doAsyncAction() {
                var gson = Gson()
                var json = gson.toJson(list)
                YDLCacheUtils.saveConfideHomeData(json)
            }
        })
    }

    /**
     * 为你推荐列表(筛选调用)
     */
    override fun recommendList(param : ConfideRecommendParam) {
        if (!RxNetTool.isConnected(mView.getContext())){
            mView.showError1("网络不给力")
            return
        }
        val disposable = mModel.recommendList(param)
                .map { it }
                .filter { it != null }
                .compose(RxUtils.applySchedulers(mView as IView))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    mView.recommendListResponse(it)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        mView.showError1(msg)
                    }
                })
    }

    /**
     * 为你推荐列表（翻页时调用）
     */
    override fun recommendListMore(param: ConfideRecommendParam) {
        if (!RxNetTool.isConnected(mView.getContext())){
            mView.showError1("网络不给力")
            return
        }
        val disposable = mModel.recommendList(param)
                .map { it }
                .filter { it != null }
                .compose(RxUtils.applySchedulers(mView as IView))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    mView.recommendListMoreResponse(it)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        mView.showError(msg)
                        mView.showError1(msg)
                    }
                })
    }
}