package ru.kirillius.pf.sdn.flow;

import lombok.RequiredArgsConstructor;
import ru.kirillius.pf.sdn.api.Networking.NetworkScope;
import ru.kirillius.pf.sdn.api.flow.CallContext;
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.*;
import java.util.regex.Pattern;

@RequiredArgsConstructor
public class SubscriptionInput extends CommonFunction {

    private final SubscriptionService subscriptionService;

    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 void apply(CallContext context) {

        var properties = context.getProperties();
        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();

        subscriptions.forEach(subscription -> bundle.add(subscription.getScope()));
    }

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

    @Override
    public List<String> getOutputNames() {
        return List.of("output");
    }
}
