package com.yidianling.ydlcommon.core.mvp.base

import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.OnLifecycleEvent
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable


/**
 * Created by haorui on 2019-08-14.
 * Des:简化版基础 Presenter，去除Model层
 */
abstract class SimplePresenter<V : IView> : IPresenter<V>, LifecycleObserver {

    open var mView: V  ?=null

    private var mCompositeDisposable: CompositeDisposable? = null

    override fun attachView(view: V) {
        this.mView = view
        if (view is LifecycleOwner) {
            (view as LifecycleOwner).lifecycle.addObserver(this)
        }
    }

    override fun detachView() {
        //保证 Activity 结束时取消所有正在执行的订阅
        unDispose()
        this.mView = null
        this.mCompositeDisposable = null
    }

    /**
     * 添加Disposable到CompositeDisposable中统一管理
     * 当Activity#onDestroy销毁时停止正在执行的任务，避免内存泄露
     *
     * 目前已使用 RxLifecycle 避免内存泄漏,此方法作为备用方案，具体使用可查看 @RxLifecycleUtils
     * @param disposable
     */
    open fun addDisposable(disposable: Disposable?) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = CompositeDisposable()
        }
        disposable?.let { mCompositeDisposable?.add(it) }
    }

    private fun unDispose() {
        //Activity 结束时取消所有正在执行的订阅
        mCompositeDisposable?.clear()
        mCompositeDisposable = null
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy(owner: LifecycleOwner) {
        owner.lifecycle.removeObserver(this)
    }

    private class MvpViewNotAttachedException internal constructor() :
        RuntimeException("Please call IPresenter.attachView(IBaseView) before" + " requesting data to the IPresenter")

    override fun destroy() {

    }
}