package com.gamedog.vididin.manager.helpers

import com.ama.core.architecture.util.DateUtil
import com.ama.core.architecture.util.SpUtil
import com.ama.core.architecture.util.eventbus.NotifyMan
import com.gamedog.vididin.VididinEvents
import com.gamedog.vididin.manager.taskbeans.TaskStateWatchAd


class DailyWatchAdTaskHelper : BaseDailyTaskHelper<TaskStateWatchAd>() {

    override val mSpKey = SpUtil.KEY_DAILY_WATCH_AD_FOR_GOLD


    init {
        registerEvents( { eventData->
            val watchedAdNum: Int = eventData?.mData as Int
            handleOneAdWatched(watchedAdNum)
        }, VididinEvents.Event_Finish_One_Ad)
    }

    override fun loadTaskFromSp() {
        val spStateBean = SpUtil.instance().getObject<TaskStateWatchAd>(mSpKey)
        if (spStateBean == null || !isTodayStatusBean(spStateBean)) {
            generateTodayTask()
        } else {
            mStateBean = spStateBean
            notifyEvents()
        }
    }

    override fun generateTodayTask() {
        mStateBean = TaskStateWatchAd(DateUtil.getCurTimeMs())
        mStateBean.initSubTaskRewardList(mTaskConfig.reward_details)
        saveState2Sp()
    }

    override fun notifyEvents() {
        NotifyMan.instance().sendEvent(VididinEvents.EVENT_DAILY_WATCHED_AD_NUM_CHANGED, null)
    }

    private fun handleOneAdWatched(newAdWatchedNum: Int) {
        mStateBean.run {
            if (!isAllTaskFinish()) {
                addWatchedCount(newAdWatchedNum)
                calculateNewState()
                saveState2Sp()
                notifyEvents()
            }
        }
    }

}