package com.ama.core.architecture.appBase

import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.ama.core.architecture.base.BaseViewModel
import com.ama.core.architecture.base.views.BaseViewsFragment
import com.ama.core.architecture.util.eventbus.NotifyMan
import com.ama.core.architecture.util.state.createAppStateView
import com.ama.core.common.util.getDataFromThemeAttr
import com.ama.core.designsystem.widget.interfaces.LoadingDialog
import com.google.android.material.R


abstract class AppViewsFragment<Binding : ViewBinding, UiState : Any, ViewModel : BaseViewModel<UiState>> :
    BaseViewsFragment<Binding, UiState, ViewModel>() {


    private var mEventCallback: NotifyMan.ICallback? = null

    protected fun registerEvents(onEvents: ((NotifyMan.NotifyData<*>?)->Unit), vararg eventTypes: Int) {
        if (mEventCallback == null) {
            mEventCallback = object : NotifyMan.ICallback(true) {
                override fun onEvent(data: NotifyMan.NotifyData<*>?) {
                    onEvents.invoke(data)
                }
            }
        }

        NotifyMan.instance().register(mEventCallback, *eventTypes)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (mEventCallback != null) {
            NotifyMan.instance().unregister(mEventCallback)
        }
    }

    // 全部使用反射来实现
//    override val viewModel: ViewModel by reflectViewModels()

    override fun createStateView(stateViewParent: ViewGroup) = createAppStateView(stateViewParent)

    // 消息的收集者，默认为Toast，子类可覆写为Snakbar等。
//    override val messageCollector: MessageCollector by lazy { ToastMessageCollector(requireContext()) }
//    override val messageCollector: MessageCollector by lazy { SnakbarViewMessageCollector(requireView())}

    // 全部使用反射来实现
//    override fun inflateViewBinding(inflater: LayoutInflater, container: ViewGroup?) =
//        reflectInflateViewBinding(inflater, container)

    override fun initLoadingDialog(loadingDialog: LoadingDialog) {
    }

    override fun initOnViewCreated() {
        super.initOnViewCreated()
        if (this is OnFragmentBackgroundListener) {
            // 设置通用背景
            binding?.root?.setBackgroundColor(requireContext().getDataFromThemeAttr(if (isBackgroundBright) R.attr.colorSurface else R.attr.colorSurfaceInverse))
        }
    }

}