package com.red.circle.game.fruit.infrastructure.database.cache.service.impl;

import com.red.circle.component.redis.service.RedisService;
import com.red.circle.game.fruit.infrastructure.database.cache.service.GameFruitTaskCacheService;
import com.red.circle.game.fruit.inner.enums.GameFruitTaskEnum;
import com.red.circle.tool.core.date.DateFormatConstant;
import com.red.circle.tool.core.date.DateUtils;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

/**
 * 摩天轮任务 缓存
 *
 * @author zongpubin on 2023/12/18
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class GameFruitTaskCacheServiceImpl implements GameFruitTaskCacheService {

  private final RedisService redisService;

  @Override
  public void recordGameFruitTaskAward(Long userId, String type) {
    if (Objects.isNull(userId)) {
      return;
    }
    redisService.increment(getGameFruitTaskAwardKey(userId, type), 1, 10, TimeUnit.DAYS);

  }


  @Override
  public Integer getGameFruitTaskAward(Long userId, String type) {

    if (Objects.isNull(userId)) {
      return 0;
    }

    return Optional.ofNullable(
        redisService.getStringToInteger(getGameFruitTaskAwardKey(userId, type))).orElse(0);
  }

  @Override
  public void addUserWinRounds(Long userId) {
    redisService.increment(getGameFruitUserWinRoundsKey(userId), 1, 3, TimeUnit.DAYS);

  }

  @Override
  public Integer getUserWinRounds(Long userId) {
    if (Objects.isNull(userId)) {
      return 0;
    }
    return Optional.ofNullable(
        redisService.getStringToInteger(getGameFruitUserWinRoundsKey(userId))).orElse(0);
  }

  @Override
  public void resetUserWinRounds(Long userId) {
    redisService.setString(getGameFruitUserWinRoundsKey(userId), 0, 3, TimeUnit.DAYS);
  }


  private String getGameFruitTaskAwardKey(Long userId, String type) {
    String key;
    key = "GAME_FRUIT_TASK:" + type + "_" + DateUtils.formatUtc(DateUtils.now(),
        DateFormatConstant.yyyyMMdd) + "_" + userId;
    if (Objects.equals(type, GameFruitTaskEnum.WEEK_COMPETITION.name()) || Objects.equals(type,
        GameFruitTaskEnum.TASK_COMPLETE_WEEK.name())) {
      key = "GAME_FRUIT_TASK:" + type + "_" + DateUtils.formatUtc(DateUtils.nowMonday(),
          DateFormatConstant.yyyyMMdd) + "_" + userId;
    }
    return key;
  }

  private String getGameFruitUserWinRoundsKey(Long userId) {
    return "GAME_FRUIT_WIN_ROUNDS:" + DateUtils.formatUtc(DateUtils.now(),
        DateFormatConstant.yyyyMMdd) + "_" + userId;
  }

}
