package core.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import core.ui.common.AbsUIDelegate
import core.ui.common.IUIListener
import io.reactivex.rxjava3.disposables.Disposable

/**
 * info
 *
 * @author ReiChin_
 */
abstract class RcBaseFragment<VB : ViewBinding> :
    Fragment(), IUIListener {

    private lateinit var _viewBinding: VB

    protected val viewBinding get() = _viewBinding

    private lateinit var mUIDelegate: AbsUIDelegate

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mUIDelegate = AbsUIDelegate.create()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _viewBinding = createViewBinding(inflater, container)
        return _viewBinding.root
    }

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

    protected abstract fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): VB

    protected abstract fun initViews(savedInstanceState: Bundle?)

    override fun showLoading(message: String?, cancelable: Boolean) {
        context?.let { mUIDelegate.showLoading(it, message, cancelable) }
    }

    override fun dismissLoading() {
        mUIDelegate.dismissLoading()
    }

    override fun showToast(message: String) {
        mUIDelegate.showToast(context, message)
    }

    override fun showNetError(throwable: Throwable) {
        mUIDelegate.showNetError(context, throwable)
    }

    override fun addDisposable(disposable: Disposable) {
        mUIDelegate.addDisposable(disposable)
    }

    override fun removeDisposable(disposable: Disposable) {
        mUIDelegate.removeDisposable(disposable)
    }

    override fun onDestroyView() {
        mUIDelegate.clearDisposable()
        super.onDestroyView()
    }

    override fun createItemDecoration(): RecyclerView.ItemDecoration? {
        return mUIDelegate.createItemDecoration(context)
    }

}