package com.ydl.ydlcommon.mvp.lce

import android.os.Bundle
import android.support.annotation.CallSuper
import android.support.v4.app.FragmentActivity
import android.view.View
import com.ydl.ydlcommon.R
import com.ydl.ydlcommon.base.BaseMvpDialogFragment
import com.ydl.ydlcommon.mvp.base.IPresenter
import com.ydl.ydlcommon.mvp.base.IView
import com.ydl.ydlcommon.mvp.lce.view.ILceViewState
import java.util.*

/**
 * Created by haorui on 2019-08-14.
 * Des: LCE 架构 BaseDialogFragment，统一处理页面加载状态
 *      LCE：L：Loading加载，C：Content加载内容，E：Error加载失败
 *
 *     【注意：StateView需设置id为：R.id.lce_state_view】
 *     【注意：ContentView需设置id为：R.id.lce_content_view】
 */
abstract class BaseLceDialogFragment<V : IView, P : IPresenter<V>> : BaseMvpDialogFragment<V, P>(), ILceView {

    protected var lceStateView: ILceViewState? = null
    protected var lceContentView: View? = null

    @CallSuper
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        lceStateView = createStateView(view)
        lceContentView = createContentView(view)

        if (lceContentView == null) {
            throw NullPointerException(
                "请检查布局文件中ContentView是否设置，id需为R.id.lce_content_view"
            )
        }

    }

    protected fun createStateView(view: View): ILceViewState {
        val stateView = view.findViewById<View>(R.id.lce_state_view)
        if (stateView is ILceViewState) {
            val viewState = stateView as ILceViewState
            viewState.setListener(object : ILceViewState.LogoLoadingListener {
                override fun onDataResetClick() {
                    loadData()
                }

                override fun onBackClick() {
                    Objects.requireNonNull<FragmentActivity>(activity).onBackPressed()
                }
            })
            return stateView
        }

        throw NullPointerException(
            "请检查布局文件中StateView是否设置，id需为R.id.lce_state_view"
        )
    }


    protected fun createContentView(view: View): View {
        return view.findViewById(R.id.lce_content_view)
    }

    override fun showLoading() {
        lceStateView!!.showLoading()
    }

    override fun hideLoading() {
        lceStateView!!.hideLoading()
    }

    override fun showContent() {
        lceContentView?.visibility = View.VISIBLE
        lceStateView!!.hideLoading()
    }

    override fun showEmpty(msg: String) {
        lceStateView!!.showEmpty(msg)
    }

    override fun showError(msg: String) {
        lceStateView!!.showError(msg)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        lceStateView = null
        lceContentView = null
    }
}