package com.yidianling.tests.home.presenter

import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.mvp.base.BasePresenter
import com.ydl.ydlcommon.utils.RxLifecycleUtils
import com.yidianling.tests.home.contract.ITestHomeContract
import com.yidianling.tests.home.model.TestHomeModelImpl
import com.yidianling.tests.home.utils.TestHomeUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer

/**
 * @author yuanwai
 * @描述:测评首页逻辑实现类
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/7/26
 */
class TestHomePresenterImpl:
        BasePresenter<ITestHomeContract.View, ITestHomeContract.Model>(), ITestHomeContract.Presenter{

    /**
     * 实例化数据模型
     */
    override fun createModel(): ITestHomeContract.Model {
        return TestHomeModelImpl()
    }

    /**
     * 测评首页数据请求
     */
    override fun newHomeRequest() {
        val disposable = mModel.newHomeRequest()
                .map { it }
                .filter { it != null }
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(Consumer {
                     mView.newHomeResponse(it)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                         mView.showError(msg)
                    }
                })
    }

    /**
     * 加载更多
     */
    override fun onLoadMore(page : Int) {
         mView.loadMoreResponse(TestHomeUtils.getRecommedDataByPage(page))
    }

    /**
     * 每日精选 换一批
     */
    override fun dailyChange() {
        val disposable = mModel.dailyChange()
                .map { it }
                .filter { it != null }
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mView))
                .subscribe(Consumer {
                     mView.dailyChangeResponse(it)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                         mView.showError(msg)
                    }
                })
    }
}