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.GameListKeys;
import com.red.circle.other.infra.database.cache.service.other.GameCacheService;
import com.red.circle.tool.core.text.StringUtils;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * ludo游戏缓存实现.
 *
 * @author pengliang on 2021/7/27
 */
@Service
@RequiredArgsConstructor
public class GameCacheServiceImpl implements GameCacheService {

  private final RedisService redisService;
  private final String LUDO_CODE = "LUDO";

  @Override
  public Integer inrJoinNumberPeopleLudo(Long gameId) {
    return redisService.increment(GameListKeys.GAME_LUDO.getKey(gameId),
            1,
            5,
            TimeUnit.MINUTES)
        .intValue();
  }

  @Override
  public boolean isJoinGameLudo(Long gameId, Long userId) {
    return Optional.ofNullable(redisService
            .getString(GameListKeys.GAME_LUDO.getKey(gameId, userId)))
        .map(StringUtils::isNotBlank)
        .orElse(Boolean.FALSE);
  }

  @Override
  public boolean setJoinGameLudo(Long gameId, Long userId) {
    return redisService
        .setIfAbsent(GameListKeys.GAME_LUDO.getKey(gameId, userId),
            1,
            5,
            TimeUnit.MINUTES);
  }

  @Override
  public void removeLudo(Long roomId, List<Long> userIds) {
    List<String> keys = userIds.stream()
        .map(userId -> GameListKeys.GAME_LUDO.getKey(roomId, userId))
        .collect(Collectors.toList());
    keys.add(GameListKeys.GAME_LUDO.getKey(roomId));
    redisService.delete(keys);
  }

}
