package com.ydl.ydlcommon.base

import android.os.Bundle
import android.view.View
import com.ydl.ydlcommon.mvp.base.IPresenter
import com.ydl.ydlcommon.mvp.base.IView
import com.ydl.ydlcommon.mvp.delegate.MvpDelegateCallback
import com.ydl.ydlcommon.mvp.delegate.MvpFragmentDelegateImpl

/**
 * Created by haorui on 2019-08-14.
 * Des:基础 MVP Fragment
 */
abstract class BaseMvpFragment<V : IView, P : IPresenter<V>> : BaseFragment(), MvpDelegateCallback<V, P>,
    IView {
    protected var mPresenter: P ?= null

    protected var mvpDelegate: MvpFragmentDelegateImpl<V, P>?=null
        get() {
            if (field == null) {
                this.mvpDelegate = MvpFragmentDelegateImpl(this, this, true)
            }
            return field
        }

    abstract override fun createPresenter(): P

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        mvpDelegate?.onViewCreated(view, savedInstanceState)
        super.onViewCreated(view, savedInstanceState)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mvpDelegate?.onDestroyView()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        mvpDelegate?.onCreate(savedInstanceState)
        super.onCreate(savedInstanceState)
    }

    override fun onDestroy() {
        super.onDestroy()
        mvpDelegate?.onDestroy()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mvpDelegate?.onSaveInstanceState(outState)
    }

    override fun getPresenter(): P {
        return mPresenter ?: throw NullPointerException("Presenter uninitialized")
    }

    override fun setPresenter(presenter: P) {
        this.mPresenter = presenter
    }

    override fun getMvpView(): V {
        return this as V
    }
}