package com.gamedog.vididin.manager.helpers

import com.ama.core.architecture.util.SpUtil
import com.ama.core.architecture.util.eventbus.NotifyMan
import com.gamedog.vididin.main.fragments.task.Task
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

abstract class BaseTaskHelper<T: Any> {
    abstract val mSpKey: String
    protected lateinit var mStateBean: T
    protected lateinit var mTaskConfig: Task
    private var mEventCallback: NotifyMan.ICallback? = null

    abstract fun loadTaskFromSp()

    suspend fun initDatas(taskConfig: Task) {
        mTaskConfig = taskConfig

        return withContext(Dispatchers.IO) {
            loadTaskFromSp()
        }
    }



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

    protected fun saveState2Sp() {
        SpUtil.instance().putObject(mSpKey, mStateBean)
    }


    fun release() {
        NotifyMan.instance().unregister(mEventCallback)
    }


}