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

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.red.circle.common.business.dto.cmd.RoomIdCmd;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.app.dto.clientobject.game.GameRoomVoteCO;
import com.red.circle.other.app.dto.clientobject.game.GameRoomVoteInfoCO;
import com.red.circle.other.infra.database.cache.service.other.GameRoomVoteCacheService;
import com.red.circle.other.infra.database.rds.entity.game.GameRoomVoteRecord;
import com.red.circle.other.infra.database.rds.service.game.GameRoomVoteRecordService;
import com.red.circle.other.inner.asserts.GameErrorCode;
import com.red.circle.tool.core.json.JacksonUtils;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 投票信息.
 * </p>
 *
 * @author pengshigang
 * @since 2022-01-05
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GameRoomVoteInfoCmdExe {

  private final GameRoomVoteCacheService gameRoomVoteCacheService;
  private final GameRoomVoteRecordService gameRoomVoteRecordService;

  public GameRoomVoteInfoCO execute(RoomIdCmd cmd) {

    GameRoomVoteRecord voteRecord = gameRoomVoteRecordService.getEfficientByRoomId(cmd.getRoomId());
    ResponseAssert.notNull(GameErrorCode.NO_GAME_RECORD_FOUND, voteRecord);

    GameRoomVoteCO roomVote = getCacheRoomVote(voteRecord.getId());
    ResponseAssert.notNull(GameErrorCode.NO_GAME_RECORD_FOUND, roomVote);

    return new GameRoomVoteInfoCO()
        .setOptionIds(Optional.ofNullable(
            JacksonUtils.readValue(gameRoomVoteCacheService
                    .getUserVoteOptionIds(roomVote.getId(), cmd.requiredReqUserId()),
                new TypeReference<List<Long>>() {
                })).orElse(Lists.newArrayList()))
        .setGameRoomVote(roomVote);
  }

  private GameRoomVoteCO getCacheRoomVote(Long voteId) {
    return gameRoomVoteCacheService.getRoomVote(voteId, GameRoomVoteCO.class);
  }

}
