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

import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.inject.Inject;

import org.springframework.context.annotation.Lazy;

import ru.yandex.qe.dispenser.domain.dao.bot.BotPreOrder;
import ru.yandex.qe.dispenser.domain.dao.bot.SyncableBotDaoImpl;
import ru.yandex.qe.dispenser.domain.index.LongIndexBase;

public class BotPreOrderDaoImpl extends SyncableBotDaoImpl<BotPreOrder> implements BotPreOrderDao {

    private final MappedPreOrderDaoImpl mappedPreOrderDao;

    @Inject
    protected BotPreOrderDaoImpl(@Lazy final MappedPreOrderDaoImpl mappedPreOrderDao) {
        super(botPreOrder -> botPreOrder.withDeletedInBot(true));
        this.mappedPreOrderDao = mappedPreOrderDao;
    }

    @Override
    public Set<Long> getPreOrderIdsByBigOrderConfigIds(final Set<Long> bigOrderConfigIds) {
        return filter(po -> bigOrderConfigIds.contains(po.getBigOrderConfigId()))
                .map(LongIndexBase::getId)
                .collect(Collectors.toSet());
    }

    @Override
    public Collection<BotPreOrder> getNotMappedPreOrderIdsByBigOrderIds(final Set<Long> bigOrderIds) {
        final Set<Long> ids = mappedPreOrderDao.getPreOrdersByBigOrderIds(bigOrderIds).keySet();
        return filter(po -> bigOrderIds.contains(po.getBigOrderId()) && !ids.contains(po.getId()))
                .collect(Collectors.toList());
    }

    @Override
    public Set<Long> getAllLinkedConfigurationIds() {
        return getAll().stream()
                .flatMap(po -> Stream.of(po.getServerId(), po.getStorageId()))
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
    }
}
