package com.red.circle.game.fruit.infrastructure.database.repository.impl;

import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.game.fruit.infrastructure.convertor.GameFruitInfraConvertor;
import com.red.circle.game.fruit.infrastructure.database.dao.GameCodeManageDAO;
import com.red.circle.game.fruit.infrastructure.database.entity.GameCodeManage;
import com.red.circle.game.fruit.infrastructure.database.repository.GameCodeManageService;
import com.red.circle.game.fruit.inner.model.dto.GameCodeManageDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 游戏配置 服务实现类.
 * </p>
 *
 * @author lisizhe on 2023-12-19 15:03
 */
@Service
@RequiredArgsConstructor
public class GameCodeManageServiceImpl extends
    BaseServiceImpl<GameCodeManageDAO, GameCodeManage> implements
    GameCodeManageService {

  private final GameFruitInfraConvertor gameFruitInfraConvertor;

  @Override
  public Set<Long> getGameIdsByCode(String code) {
    return Optional.ofNullable(
        query().select(GameCodeManage::getGameId).eq(GameCodeManage::getGameCode, code).list())
        .map(list -> list.stream().map(GameCodeManage::getGameId).collect(Collectors.toSet()))
        .orElse(CollectionUtils.newHashSet());
  }

  @Override
  public void add(GameCodeManage gameCodeManage) {
    GameCodeManage game = query().eq(GameCodeManage::getGameId, gameCodeManage.getGameId())
        .getOne();
    if (Objects.nonNull(game)) {
      return;
    }
    save(gameCodeManage);
  }

  @Override
  public void del(Long gameId) {
    removeById(gameId);
  }

  @Override
  public Map<Long, GameCodeManageDTO> mapGameCodeManage(Set<Long> gameIds) {
    return Optional.ofNullable(query().in(GameCodeManage::getGameId, gameIds)
            .last(PageConstant.formatLimit(gameIds.size())).list())
        .map(list -> list.stream().collect(
            Collectors.toMap(GameCodeManage::getGameId,
                gameFruitInfraConvertor::toGameCodeManageDTO)))
        .orElse(CollectionUtils.newHashMap());
  }
}
