package com.game.business.task;


import com.alibaba.fastjson.JSONObject;
import com.game.business.domain.AppGame;
import com.game.business.service.IAppGameService;
import com.game.business.websocket.server.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class AppGameHanaderTask {

    @Autowired
    private IAppGameService appGameService;

    @Autowired
    private AppGameLotteryAutoTask appGameLotteryAutoTask;

    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${websocket.switch}")
    private Boolean taskSwitch;

    @Async("asyncExecutor")
    public void initGameCountdown(String gameCode){

        if(!taskSwitch){
            return;
        }

        AppGame appGame = appGameService.selectAppGameByCode(gameCode);

        if(appGame == null) return;

        int countdown = 52;

        JSONObject jsonObject = new JSONObject();

        while (true){

            try {

                // 推送倒计时
                jsonObject.put("type", "1");
                jsonObject.put("countdown", countdown);
                webSocketServer.sendMessageAll(jsonObject.toJSONString());

                // 开奖
                if(countdown == 7){
                    appGameLotteryAutoTask.autoTask(appGame.getId());
                }

                // 更新游戏信息
                appGameLotteryAutoTask.updateAppGameTime(appGame.getClassifyId(), appGame.getId(), countdown);

                // 重新开启倒计时
                if(countdown ==  0){
                    countdown = 53;
                }

                Thread.sleep(1000L);
                countdown --;
            }catch (Exception e){
                e.printStackTrace();
                break;
            }
        }
    }
}
