package com.red.circle.other.infra.database.mongo.entity.game.ludo;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.num.ArithmeticUtils;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * ludo游戏运行模型.
 *
 * @author pengliang on 2022/3/8
 */
@Data
@Accessors(chain = true)
@Document("game_ludo_run")
public class GameLudoRun implements Serializable {

  private static final long serialVersionUID = 1L;

  /**
   * 主键标识.
   */
  @JsonSerialize(using = ToStringSerializer.class)
  private Long id;

  /**
   * 归属系统.
   */
  private String sysOrigin;

  /**
   * 房间id.
   */
  @JsonSerialize(using = ToStringSerializer.class)
  private Long roomId;

  /**
   * 创建游戏用户id.
   */
  @JsonSerialize(using = ToStringSerializer.class)
  private Long userId;

  /**
   * 游戏状态.
   */
  private GameStatus gameStatus;

  /**
   * 游戏状态事件.
   */
  private GameStatusEvent gameStatusEvent;

  /**
   * 加入金额.
   */
  private BigDecimal joinAmount;

  /**
   * 锁定座位.
   */
  private String lockSeat;

  /**
   * 玩家信息.
   */
  private List<GameLudoPlayer> players;

  /**
   * 创建事件.
   */
  private Timestamp createTime;

  /**
   * 玩家数量.
   */
  public int playersSize() {
    return CollectionUtils.isEmpty(players) ? 0 : players.size();
  }

  /**
   * 获取指定颜色玩家信息.
   */
  @JsonIgnore
  public GameLudoPlayer getPlayerByColor(String color) {
    return players.stream()
        .filter(details -> Objects.equals(details.getCheckerboardColor().name(), color))
        .findFirst()
        .orElse(null);
  }

  /**
   * 奖金.
   */
  public BigDecimal bonusRatio() {
    return ArithmeticUtils.multiplyRatioRemain(players.stream()
        .map(GameLudoPlayer::getConsumeJoinAmount)
        .reduce(BigDecimal.ZERO, BigDecimal::add)
        .setScale(0, RoundingMode.DOWN), 0.1);
  }

  /**
   * 是否存在玩家.
   */
  public boolean exitsPlayer(Long playerId) {
    for (GameLudoPlayer player : players) {
      if (Objects.equals(player.getPlayerProfile().getId(), playerId)) {
        return true;
      }
    }
    return false;
  }

}
