package ru.yandex.qe.dispenser.ws.allocation;

import org.springframework.stereotype.Component;
import ru.yandex.qe.dispenser.domain.dictionaries.impl.PerCampaignFrontDictionariesManager;
import ru.yandex.qe.dispenser.domain.dictionaries.model.CampaignProvidersSettingsDictionary;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class AllocationHelper {

    private final PerCampaignFrontDictionariesManager perCampaignFrontDictionariesManager;

    public AllocationHelper(PerCampaignFrontDictionariesManager perCampaignFrontDictionariesManager) {
        this.perCampaignFrontDictionariesManager = perCampaignFrontDictionariesManager;
    }

    public Map<Long, Boolean> hasIoResourcesAvailableInCampaign(Set<Long> providerIds,
                                                                long campaignId) {
        final Optional<CampaignProvidersSettingsDictionary> perCampaignProviderSettings = perCampaignFrontDictionariesManager
                .getPerCampaignProviderSettings(campaignId);
        final Map<Long, CampaignProvidersSettingsDictionary.Provider> settingsByServiceId = perCampaignProviderSettings
                .map(c -> c.getProviders()
                        .stream()
                        .collect(Collectors.toMap(CampaignProvidersSettingsDictionary.Provider::getId, Function.identity())))
                .orElse(Collections.emptyMap());
        final Map<Long, Boolean> result = new HashMap<>();
        for (Long providerId : providerIds) {
            final CampaignProvidersSettingsDictionary.Provider providerSettings = settingsByServiceId.get(providerId);
            final boolean hasIoResources = providerSettings != null && providerSettings.getResources()
                    .stream()
                    .anyMatch(r -> r.getKey().startsWith("io"));
            result.put(providerId, hasIoResources);
        }
        return result;
    }

    public boolean hasIoResourcesAvailableInCampaign(long providerId,
                                                     long campaignId) {
        return hasIoResourcesAvailableInCampaign(Set.of(providerId), campaignId).getOrDefault(providerId, false);
    }
}
