package ru.yandex.webmaster3.monitoring.solomon.trigger;

import com.fasterxml.jackson.databind.JsonNode;
import ru.yandex.webmaster3.monitoring.solomon.SolomonTriggerProperty;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author avhaliullin
 */
public class SolomonTriggerPropertiesSet {
    private final List<SolomonTriggerProperty> properties;

    private SolomonTriggerPropertiesSet(List<SolomonTriggerProperty> properties) {
        this.properties = properties;
    }

    public Optional<JsonNode> findProperty(PropertyKey propertyKey, String propertyName) {
        for (SolomonTriggerProperty property : properties) {
            if (!property.getName().equals(propertyName)) {
                continue;
            }
            boolean matches = true;
            for (Map.Entry<String, String> entry : property.getLabels().entrySet()) {
                String value = propertyKey.getLabels().get(entry.getKey());
                if (value == null || !value.equals(entry.getValue())) {
                    matches = false;
                    break;
                }
            }
            if (matches) {
                return Optional.of(property.getValue());
            }
        }
        return Optional.empty();
    }

    public static SolomonTriggerPropertiesSet createFromList(List<SolomonTriggerProperty> props) {
        return new SolomonTriggerPropertiesSet(
                props.stream()
                        .sorted(Comparator.comparing((SolomonTriggerProperty prop) -> prop.getLabels().size()).reversed())// более специфичные селекторы имеют приоритет
                        .collect(Collectors.toList())
        );
    }
}
