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

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.google.common.collect.Lists;
import com.red.circle.framework.dto.ClientObject;
import com.red.circle.tool.core.date.LocalDateTimeUtils;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.num.NumUtils;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * <p>
 * 转盘游戏记录.
 * </p>
 *
 * @author houyong
 * @since 2021-03-03
 */
@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
public class RoomTurntableGameCO extends ClientObject {

  private static final long serialVersionUID = 1L;

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

  /**
   * 游戏ID.
   */
  @JsonSerialize(using = ToStringSerializer.class)
  private Long gameId;

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

  /**
   * 房主用户id.
   */
  @JsonSerialize(using = ToStringSerializer.class)
  private Long homeownerUserId;

  /**
   * 入场费.
   */
  private BigDecimal gameGolds;

  /**
   * 游戏状态.
   */
  private String status;

  /**
   * 角色.
   */
  private String roles;

  /**
   * 游戏创建时间.
   */
  private Timestamp createTime;

  /**
   * 剩余时间.
   */
  private Long surplusTime;

  /**
   * 参与游戏用户.
   */
  private List<RoomTurntableGameParticipatingUserCO> participatingUsers;

  /**
   * 剩余时间.
   */
  public Long getSurplusTime() {
    return TimestampUtils.expiredIntervalMillisecond(TimestampUtils.now(),
        TimestampUtils.convert(LocalDateTimeUtils
            .convert(createTime).plusMinutes(2)));
  }

  public void addParticipatingUsers(RoomTurntableGameParticipatingUserCO user) {
    if (Objects.isNull(participatingUsers)) {
      participatingUsers = Lists.newArrayList();
    }
    participatingUsers.add(user);
  }

  public void addParticipatingUsers(List<RoomTurntableGameParticipatingUserCO> user) {
    if (Objects.isNull(participatingUsers)) {
      participatingUsers = Lists.newArrayList();
    }
    participatingUsers.addAll(user);
  }

  public RoomTurntableGameParticipatingUserCO markJackpot() {
    List<RoomTurntableGameParticipatingUserCO> participatingUsers = getParticipatingUsers();
    RoomTurntableGameParticipatingUserCO jackpot = participatingUsers
        .get(NumUtils.randomBetween(0, participatingUsers.size() - 1));
    this.participatingUsers = participatingUsers.stream()
        .peek(participatingUser -> participatingUser
            .setJackpot(
                Objects.equals(participatingUser.getId(), jackpot.getId()) ? Boolean.TRUE : null))
        .collect(Collectors.toList());
    return jackpot;
  }


}
