package com.ydl.ydlcommon.base

import android.os.Bundle
import androidx.fragment.app.DialogFragment
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 DialogFragment
 */
abstract class BaseMvpDialogFragment<V : IView, P : IPresenter<V>> : DialogFragment(), 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?) {
        super.onViewCreated(view, savedInstanceState)
        mvpDelegate?.onViewCreated(view, savedInstanceState)
    }

    override fun onDestroyView() {
        val dialog = dialog
        if (dialog != null && retainInstance) {
            dialog.setDismissMessage(null)
        }

        super.onDestroyView()
        mvpDelegate?.onDestroyView()
    }

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

    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
    }
}