package com.red.circle.other.app.dto.cmd.game;

import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.ResponseErrorCode;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.text.StringUtils;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * 游戏结算.
 *
 * @author pengliang on 2021/7/27
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class GameLudoEndCmd extends AppExtCommand {

  /**
   * 游戏id.
   *
   * @eo.required
   */
  @NotNull(message = "id required.")
  private Long id;

  /**
   * 类型.
   *
   * @eo.required
   */
  @NotBlank(message = "endType required.")
  private String endType;

  /**
   * 游戏结束排名.
   *
   * @eo.required
   */
  @NotNull(message = "rankings required.")
  private List<Ranking> rankings;

  public String getVictory() {
    return rankings.get(0).getCheckerboardColor();
  }

  public Map<String, Integer> rankingsToMap() {
    return rankings.stream()
        .collect(Collectors.toMap(Ranking::getCheckerboardColor, Ranking::getRanking));
  }

  public void checkFilterRanking() {
    if (CollectionUtils.isEmpty(rankings)) {
      ResponseAssert.failure(ResponseErrorCode.REQUEST_PARAMETER_ERROR, "rankings not null.");
    }

    rankings = rankings.stream().peek(ranking -> {
      if (StringUtils.isBlanks(ranking.getCheckerboardColor())) {
        ResponseAssert.failure(ResponseErrorCode.REQUEST_PARAMETER_ERROR,
            "rankings.checkerboardColor exists blank.");
      }
      if (Objects.isNull(ranking.getRanking())) {
        ResponseAssert.failure(ResponseErrorCode.REQUEST_PARAMETER_ERROR,
            "rankings.ranking exists null.");
      }
      ranking.setCheckerboardColor(ranking.getCheckerboardColor().trim());
      ranking.setRanking(ranking.getRanking());
    }).sorted(Comparator.comparing(Ranking::getRanking)).collect(Collectors.toList());
  }

  @Data
  static class Ranking implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 棋盘颜色.
     */
    private String checkerboardColor;

    /**
     * 排名.
     */
    private Integer ranking;
  }
}
