package com.ydl.ydlcommon.mvp.lce

import androidx.annotation.CallSuper
import android.view.View
import com.ydl.ydlcommon.base.BaseMvpActivity
import com.ydl.ydlcommon.mvp.base.IPresenter
import com.ydl.ydlcommon.mvp.base.IView
import com.ydl.ydlcommon.mvp.lce.view.ILceViewState

/**
 * Created by haorui on 2019-08-14.
 * Des: LCE 架构 BaseActivity，统一处理页面加载状态
 *      LCE：L：Loading加载，C：Content加载内容，E：Error加载失败
 *
 *     【注意：StateView需继承 ILceViewState 接口】
 */
abstract class BaseLceActivity<V : IView, P : IPresenter<V>> : BaseMvpActivity<V, P>(), ILceView {

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

    @CallSuper
    override fun onContentChanged() {
        super.onContentChanged()
        lceStateView = createStateView()
        lceContentView = createContentView()
    }

    private fun createStateView(): ILceViewState {
        val stateView:View? = findViewById<View>(getStateViewId())

        if (stateView != null && stateView is ILceViewState) {
            val viewState = stateView as ILceViewState
            viewState.setListener(object : ILceViewState.LogoLoadingListener {
                override fun onDataResetClick() {
                    reLoadData()
                }

                override fun onBackClick() {
                    this@BaseLceActivity.onBackPressed()
                }
            })
            return stateView
        }

        throw NullPointerException(
            "请检查布局文件中 StateView 是否设置，StateView 需继承 ILceViewState 接口 , className:${this.javaClass.simpleName}"
        )
    }

    private fun createContentView(): View {
       val contentView: View? = findViewById<View>(getContentViewId())
           ?: throw NullPointerException(
               "请检查布局文件中 ContentView 是否设置 , className:${this.javaClass.simpleName}"
           )

        return  contentView!!
    }

    /**
     * 获取 ContentView 控件ID
     */
    abstract fun getContentViewId(): Int

    /**
     * 获取 StateVie 控件 ID
     */
    abstract fun getStateViewId(): Int

    override fun showLoading() {
        lceStateView?.showLoading()
        lceContentView?.visibility = View.INVISIBLE
    }

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

    }

    override fun showEmpty(msg: String) {
        lceContentView?.visibility = View.INVISIBLE
        lceStateView?.showEmpty(msg)
    }

    override fun showError(msg: String) {
        lceContentView?.visibility = View.INVISIBLE
        lceStateView?.showError(msg)
    }

}


