package com.gamedog.vididin.manager.helpers

import com.ama.core.architecture.util.SpUtil
import com.ama.core.architecture.util.eventbus.NotifyMan
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

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

    abstract fun loadTaskFromSp()

    suspend fun setConfigDatas(taskConfig: C) {
        mTaskConfig = taskConfig

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

    open fun onDateChanged() {
        // TODO - sub class override this methods if daily task
    }


    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 getStatusBean() : T {
        return mStateBean
    }

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


}