package at.procon.eventhub.importing.extraction;

import at.procon.eventhub.importing.ImportRunRequest;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ExtractionDefinitionRegistry<R extends ImportRunRequest> {

    private final Map<String, ExtractionDefinition<R>> definitionsByCode;

    protected ExtractionDefinitionRegistry(List<ExtractionDefinition<R>> definitions) {
        this.definitionsByCode = definitions.stream()
                .collect(Collectors.toUnmodifiableMap(definition -> normalize(definition.code()), Function.identity()));
    }

    public Optional<ExtractionDefinition<R>> findByCode(String code) {
        return Optional.ofNullable(definitionsByCode.get(normalize(code)));
    }

    public Set<String> supportedCodes() {
        return definitionsByCode.keySet();
    }

    public List<ExtractionDefinition<R>> definitions() {
        return definitionsByCode.values().stream()
                .sorted(Comparator.comparing(ExtractionDefinition::code))
                .toList();
    }

    private String normalize(String value) {
        return value == null ? "" : value.trim().toUpperCase(Locale.ROOT);
    }
}
