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

import com.red.circle.component.redis.service.RedisService;
import com.red.circle.other.infra.database.cache.service.user.UserCpValueCacheService;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * cp用户值累计.
 *
 * @author pengshigang on 2022/5/29.
 */
@Service
@RequiredArgsConstructor
public class UserCpValueCacheServiceImpl implements UserCpValueCacheService {

  private final RedisService redisService;

  @Override
  public void incr(Long userId1, Long userId2, Long quantity) {
    redisService.increment(getKey(userId1, userId2), quantity);
  }

  @Override
  public Long getValue(Long userId1, Long userId2) {

    Long val1 = Optional.ofNullable(redisService.getStringToLong(
        getKey(userId1, userId2))).orElse(0L);

    Long val2 = Optional.ofNullable(redisService.getStringToLong(
        getKey(userId2, userId1))).orElse(0L);

    return val1 + val2;
  }

  @Override
  public void remove(Long userId1, Long userId2) {
    redisService.delete(getKey(userId1, userId2));
    redisService.delete(getKey(userId2, userId1));

  }

  private String getKey(Long userId1, Long userId2) {
    return "USER_CP_RANK_INTEGRAL:" + userId1 + "_" + userId2;
  }

}

