package com.red.circle.other.app.common.game;

import com.red.circle.other.app.convertor.game.GameLudoAppConvertor;
import com.red.circle.other.infra.database.cache.service.other.GameCacheService;
import com.red.circle.other.infra.database.mongo.entity.game.ludo.GameLudoRun;
import com.red.circle.other.infra.database.mongo.service.game.GameLudoRunService;
import com.red.circle.other.infra.database.rds.entity.game.GameLudoHistory;
import com.red.circle.other.infra.database.rds.entity.game.GameLudoPlayers;
import com.red.circle.other.infra.database.rds.service.game.GameLudoHistoryService;
import com.red.circle.other.infra.database.rds.service.game.GameLudoPlayersService;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * @author pengliang on 2022/3/8
 */
@Component
@RequiredArgsConstructor
public class GameLudoCommon {

  private final GameCacheService gameCacheService;
  private final GameLudoAppConvertor gameLudoAppConvertor;
  private final GameLudoRunService gameLudoRunService;
  private final GameLudoHistoryService gameLudoHistoryService;
  private final GameLudoPlayersService gameLudoPlayersService;

  public void historyProcessing(GameLudoRun gameLudoRun) {
    historyProcessing(gameLudoRun, "");
  }

  public void historyProcessing(GameLudoRun gameLudoRun, String victoryColor) {
    // 清理缓存
    gameCacheService.removeLudo(gameLudoRun.getRoomId(),
        gameLudoRun.getPlayers().stream().map(player -> player.getPlayerProfile().getId()).collect(
            Collectors.toList()));
    // 清理游戏运行数据
    gameLudoRunService.remove(gameLudoRun.getId());

    // 保存游戏档案
    GameLudoHistory gameLudoHistory = gameLudoAppConvertor.entityToGameLudoHistory(gameLudoRun);
    gameLudoHistory.setId(IdWorkerUtils.getId());
    gameLudoHistory.setVictoryColor(victoryColor);
    gameLudoHistory.setBonus(gameLudoRun.bonusRatio());
    gameLudoHistory.setPlayerSize(gameLudoRun.playersSize());
    gameLudoHistory.setCreateTime(gameLudoRun.getCreateTime());
    gameLudoHistoryService.save(gameLudoHistory);

    if (gameLudoHistory.getPlayerSize() <= 0) {
      return;
    }

    gameLudoPlayersService.saveBatch(
        gameLudoRun.getPlayers().stream().map(player -> new GameLudoPlayers()
            .setGameId(gameLudoHistory.getId())
            .setUserId(player.getPlayerProfile().getId())
            .setConsumeJoinAmount(player.getConsumeJoinAmount())
            .setCheckerboardColor(Objects.toString(player.getCheckerboardColor()))
            .setInitiator(player.getInitiator())
            .setRankingIndex(
                Objects.isNull(player.getRankingIndex()) ? 0 : player.getRankingIndex())
        ).collect(Collectors.toList()));
  }

}
