package com.ydl.ydlcommon.mvp.base

import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.OnLifecycleEvent


/**
 * Created by haorui on 2019-08-14.
 * Des:基础 Presenter
 */
abstract class BasePresenter< V : IView,M : IModel> : IPresenter<V>, LifecycleObserver {

    open lateinit var mModel: M
    open lateinit var mView: V
    abstract fun createModel(): M

    override fun attachView(view: V) {
        this.mView = view
        mModel = createModel()
        if (view is LifecycleOwner) {
            (view as LifecycleOwner).lifecycle.addObserver(this)
            if (mModel != null && mModel is LifecycleObserver) {
                (view as LifecycleOwner).lifecycle.addObserver(mModel as LifecycleObserver)
            }
        }
    }

    override fun detachView() {
        //保证 Activity 结束时取消所有正在执行的订阅

    }

    @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() {

    }


}