package com.red.circle.other.app.command.game.turntable;

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.mq.business.model.event.game.GameTurntableEvent;
import com.red.circle.mq.rocket.business.producer.GameMqMessage;
import com.red.circle.other.app.common.game.GameTurntableCommon;
import com.red.circle.other.app.dto.clientobject.game.RoomTurntableGameCO;
import com.red.circle.other.app.dto.clientobject.game.RoomTurntableGameParticipatingUserCO;
import com.red.circle.other.app.dto.cmd.game.GameTurntableGameIdCmd;
import com.red.circle.other.infra.enums.game.TurntableGameStatus;
import com.red.circle.other.inner.asserts.RoomErrorCode;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 开始转盘游戏.
 *
 * @author pengliang on 2021/3/19
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GameTurntableStartCmdExe {

  private final GameMqMessage gameMqMessage;
  private final GameTurntableCommon gameTurntableCommon;

  public RoomTurntableGameCO execute(GameTurntableGameIdCmd cmd) {
    RoomTurntableGameCO roomTurntableGame = gameTurntableCommon
        .getProcessingGameByGameId(cmd.getGameId());

    // 9100 游戏不存在
    ResponseAssert.notNull(RoomErrorCode.GAME_NOT_EXIST, roomTurntableGame);

    // 9102 游戏进行中
    ResponseAssert.isTrue(RoomErrorCode.GAME_PROCESSING,
        Objects.equals(roomTurntableGame.getStatus(), TurntableGameStatus.WAIT.name()));

    // 9106 开始游戏必须是发起者
    ResponseAssert.isTrue(RoomErrorCode.START_GAME_MUST_SPONSOR,
        Objects.equals(cmd.getReqUserId(), roomTurntableGame.getUserId()));

    // 1014 数据异常
    ResponseAssert.notNull(CommonErrorCode.DATA_ERROR, roomTurntableGame);

    // 1014 数据异常
    ResponseAssert.isTrue(CommonErrorCode.DATA_ERROR,
        CollectionUtils.isNotEmpty(roomTurntableGame.getParticipatingUsers()));

    // 计算获奖 + 淘汰用户
    RoomTurntableGameParticipatingUserCO jackpot = roomTurntableGame.markJackpot();
    // 标记中奖用户
    gameTurntableCommon.jackpot(cmd.getGameId(), jackpot.getUserId());
    // 变更状态
    gameTurntableCommon.updateGameStatus(cmd.getGameId(), TurntableGameStatus.PROCESSING);

    gameMqMessage.turntableDelayed(IdWorkerUtils.getIdStr(), new GameTurntableEvent()
        .setType(0)
        .setGameId(roomTurntableGame.getGameId())
        .setStartDeliverTime(
            TimestampUtils.nowPlusSeconds(roomTurntableGame.getParticipatingUsers().size() * 3L + 5)
                .getTime())
        .setSysOrigin(cmd.requireReqSysOriginEnum())
    );
    return roomTurntableGame;
  }

}
