package com.red.circle.other.infra.database.cache.service.other.impl;


import com.red.circle.component.redis.service.RedisService;
import com.red.circle.other.infra.database.cache.key.GameRoomVoteKeys;
import com.red.circle.other.infra.database.cache.service.other.GameRoomVoteCacheService;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 房间投票.
 * </p>
 *
 * @author pengshigang
 * @since 2022-01-04
 */
@Service
@RequiredArgsConstructor
public class GameRoomVoteCacheServiceImpl implements GameRoomVoteCacheService {

  private final RedisService redisService;

  @Override
  public Long getOptionVotes(Long voteId, Long optionId) {
    return redisService.increment(
        GameRoomVoteKeys.GAME_OPTION_VOTES.getKey(voteId + "_" + optionId), 1, 80,
        TimeUnit.MINUTES);
  }

  @Override
  public void cacheRoomVote(Long voteId, String data) {
    redisService.setString(GameRoomVoteKeys.ROOM_VOTE.getKey(voteId),
        data, 80, TimeUnit.MINUTES);
  }

  @Override
  public <T> T getRoomVote(Long voteId, Class<T> clazz) {
    return redisService.getStringToObject(GameRoomVoteKeys.ROOM_VOTE.getKey(voteId), clazz);
  }

  @Override
  public void deleteRoomVote(Long voteId) {

    if (Objects.isNull(voteId)) {
      return;
    }
    redisService.delete(GameRoomVoteKeys.ROOM_VOTE.getKey(voteId));
  }

  @Override
  public void cacheSignUserVote(Long voteId, Long userId) {

    redisService.setString(GameRoomVoteKeys.ROOM_VOTE_USER_SIGN.getKey(voteId + "_" + userId),
        Boolean.TRUE, 60, TimeUnit.MINUTES);
  }

  @Override
  public Boolean getSignUserVote(Long voteId, Long userId) {

    return Optional.ofNullable(redisService.getStringToBool(
            GameRoomVoteKeys.ROOM_VOTE_USER_SIGN.getKey(voteId + "_" + userId)))
        .orElse(Boolean.FALSE);
  }

  @Override
  public void cacheUserVoteOptionIds(Long voteId, Long userId, String optionIds) {

    redisService.setString(GameRoomVoteKeys.ROOM_VOTE_USER_OPTION_ID.getKey(voteId + "_" + userId),
        optionIds, 60, TimeUnit.MINUTES);
  }

  @Override
  public String getUserVoteOptionIds(Long voteId, Long userId) {

    return redisService.getString(
        GameRoomVoteKeys.ROOM_VOTE_USER_OPTION_ID.getKey(voteId + "_" + userId));
  }
}
