package ru.yandex.qe.dispenser.domain.dao.bot.configuration;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.inject.Inject;

import org.springframework.context.annotation.Lazy;

import ru.yandex.qe.dispenser.domain.bot.Configuration;
import ru.yandex.qe.dispenser.domain.dao.bot.BotConfiguration;
import ru.yandex.qe.dispenser.domain.dao.bot.CompleteBotConfiguration;
import ru.yandex.qe.dispenser.domain.dao.bot.SyncableBotDaoImpl;
import ru.yandex.qe.dispenser.domain.dao.bot.preorder.BotPreOrderDaoImpl;

public class BotConfigurationDaoImpl extends SyncableBotDaoImpl<BotConfiguration<? extends Configuration>>
        implements BotConfigurationDao {

    private final BotPreOrderDaoImpl preOrderDao;

    @Inject
    public BotConfigurationDaoImpl(@Lazy final BotPreOrderDaoImpl preOrderDao) {
        super(c -> c.withDeletedInBot(true));
        this.preOrderDao = preOrderDao;
    }

    @Override
    public Map<Long, CompleteBotConfiguration> getConfigurationsInBigOrders(final Set<Long> bigOrderIds) {
        final Set<Long> configurationIds = new HashSet<>();

        preOrderDao.filter(po -> bigOrderIds.contains(po.getBigOrderId()))
                .forEach(po -> {
                    final Long serverId = po.getServerId();
                    if (serverId != null) {
                        configurationIds.add(serverId);
                    }
                    final Long storageId = po.getStorageId();
                    if (storageId != null) {
                        configurationIds.add(storageId);
                    }
                });

        return filter(c -> configurationIds.contains(c.getId()))
                .collect(Collectors.toMap(BotConfiguration::getId, bc -> (CompleteBotConfiguration) bc));
    }
}
