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

import com.red.circle.common.business.core.enums.GameStateEnum;
import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.common.business.dto.cmd.app.AppIdLongCmd;
import com.red.circle.external.inner.endpoint.message.ImGroupClient;
import com.red.circle.external.inner.model.cmd.message.BroadcastGroupMsgBodyCmd;
import com.red.circle.external.inner.model.enums.message.GroupMessageTypeEnum;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.app.dto.clientobject.game.GameIndoorTeamPkMsgCO;
import com.red.circle.other.infra.database.rds.entity.game.GameIndoorTeamPkRecord;
import com.red.circle.other.infra.database.rds.service.game.GameIndoorTeamPkRecordService;
import com.red.circle.other.infra.enums.game.GameRoomPkTypeEnum;
import com.red.circle.other.inner.asserts.GameErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 房间内团队PK - 取消自己发布的PK.
 *
 * @author pengshigang on 2022/3/3
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GameCancelTeamPkCmdExe {

  private final ImGroupClient imGroupClient;
  private final GameIndoorTeamPkRecordService gameIndoorTeamPkRecordService;

  public void execute(AppIdLongCmd cmd) {

    GameIndoorTeamPkRecord pkRecord = getWaitById(cmd.getId());
    ResponseAssert.notNull(GameErrorCode.GAME_NOT_EXIST, pkRecord);
    pkRecord.setSysOrigin(cmd.getReqSysOrigin().getOrigin());
    gameIndoorTeamPkRecordService.updateGameOverById(cmd.getId());
    sendMsg(pkRecord);
  }

  private void sendMsg(GameIndoorTeamPkRecord game) {
    imGroupClient
        .sendMessageBroadcast(
            BroadcastGroupMsgBodyCmd.builder().type(GroupMessageTypeEnum.GAME_INDOOR_TEAM_PK)
                .data(new GameIndoorTeamPkMsgCO()
                    .setMsgType(GameRoomPkTypeEnum.GAME_ROOM_PK_OVER.name())
                    .setRoomId(game.getRoomId())
                )
                .toPlatform(SysOriginPlatformEnum.valueOf(game.getSysOrigin()))
                .build());
  }

  private GameIndoorTeamPkRecord getWaitById(Long id) {
    return gameIndoorTeamPkRecordService.getByIdByStatus(id, GameStateEnum.WAITING);
  }

}
