package ru.kirillius.pf.sdn.pipeline;

import lombok.RequiredArgsConstructor;
import ru.kirillius.pf.sdn.api.Networking.NetworkScope;
import ru.kirillius.pf.sdn.api.pipeline.PipelineFunction;
import ru.kirillius.pf.sdn.api.properties.PropertyDescriptor;
import ru.kirillius.pf.sdn.api.properties.PropertyType;
import ru.kirillius.pf.sdn.service.SubscriptionService;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@RequiredArgsConstructor
public class SubscriptionInput implements PipelineFunction {

    private final SubscriptionService subscriptionService;

    @Override
    public NetworkScope apply(NetworkScope source, Map<String, String> properties) {
        var subscriptions = subscriptionService.getSubscriptions();
        if (properties.containsKey(NAMES)) {
            var names = properties.get(NAMES);
            var filter = Arrays.stream(names.split(Pattern.quote(","))).filter(s -> !s.isBlank()).toList();
            subscriptions = subscriptions.stream().filter(s -> filter.contains(s.getName())).toList();
        }

        var bundle = new NetworkScope();
        bundle.add(source);
        subscriptions.forEach(subscription -> bundle.add(subscription.getScope()));
        return bundle;
    }

    private final static String NAMES = "names";
    private final static Map<String, PropertyDescriptor> properties;

    static {
        properties = new HashMap<>();
        properties.put(NAMES, PropertyDescriptor.builder().type(PropertyType.SUBSCRIPTION).array(true).required(false).defaultValue(null).build());
    }

    @Override
    public Map<String, PropertyDescriptor> getProperties() {
        return Collections.unmodifiableMap(properties);
    }
}
