package com.seer.teach.teacher.stateMachine.action;

import com.seer.teach.common.enums.teacher.LessonStateEnum;
import com.seer.teach.common.enums.teacher.LessonStateEvent;
import com.seer.teach.teacher.common.utils.CountdownExecutorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.action.Action;
import org.springframework.stereotype.Component;

/**
 * 音频播放完成后启动倒计时动作
 */
@Slf4j
@Component
public class StartAudioCountdownAction implements Action<LessonStateEnum, LessonStateEvent> {

    private final static Integer COUNT_TIME_SECONDS = 5;

    @Override
    public void execute(StateContext<LessonStateEnum, LessonStateEvent> context) {
        Integer userId = Integer.parseInt(context.getStateMachine().getId());
        // 取消已有倒计时
        CountdownExecutorUtil.cancel(userId);
        // 启动新倒计时
        CountdownExecutorUtil.start(userId, COUNT_TIME_SECONDS, () -> {
            log.info("倒计时结束，发送 AUDIO_FINISH_TIMEOUT");
            context.getStateMachine().sendEvent(LessonStateEvent.AUDIO_FINISH_TIMEOUT);
        });
        log.info("用户[{}] 音频播放完毕，启动{}秒倒计时", userId, COUNT_TIME_SECONDS);
    }
}
