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.GameRedPacketKeys;
import com.red.circle.other.infra.database.cache.service.other.GameRedPacketCacheService;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 游戏红包缓存服务.
 *
 * @author pengliang on 2021/5/17
 */
@Service
@RequiredArgsConstructor
public class GameRedPacketCacheServiceImpl implements GameRedPacketCacheService {

  private final RedisService redisService;

  @Override
  public void push(Long redPacketId, List<Integer> amounts) {
    redisService.listPushAll(gameRedPacketQueueKey(redPacketId),
        amounts.stream().map(String::valueOf).collect(
            Collectors.toList()));
  }

  @Override
  public String pop(Long redPacketId) {
    Object popAmount = redisService.listPop(gameRedPacketQueueKey(redPacketId));
    return Objects.nonNull(popAmount) ? popAmount.toString() : "0";
  }

  @Override
  public void setReceiveStatus(Long redPacketId, Long userId, String status) {
    redisService.setString(gameRedPacketReceiveStatusKey(redPacketId, userId), status, 1,
        TimeUnit.HOURS);
  }

  @Override
  public String getReceiveStatus(Long redPacketId, Long userId) {
    return redisService.getString(gameRedPacketReceiveStatusKey(redPacketId, userId));
  }

  private String gameRedPacketReceiveStatusKey(Long userId, Long redPacketId) {
    return GameRedPacketKeys.STATUS.getKey(userId, redPacketId);
  }

  private String gameRedPacketQueueKey(Long redPacketId) {
    return GameRedPacketKeys.QUEUE.getKey(redPacketId);
  }

}
