package ru.kirillius.pf.sdn.pipeline;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ru.kirillius.pf.sdn.Util.IPv4Util;
import ru.kirillius.pf.sdn.api.Networking.NetworkScope;
import ru.kirillius.pf.sdn.api.pipeline.PipelineFunction;
import ru.kirillius.pf.sdn.api.properties.IntegerConstraint;
import ru.kirillius.pf.sdn.api.properties.PropertyDescriptor;
import ru.kirillius.pf.sdn.api.properties.PropertyType;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
public class MergeWithCoverageSubnetFilter implements PipelineFunction {
    private final static String USAGE = "usage";

    @Override
    public NetworkScope apply(NetworkScope source, Map<String, String> properties) {
        var usage = properties.containsKey(USAGE) ? Integer.parseInt(properties.get(USAGE)) : 75;
        if (usage < 51) {
            usage = 51;
        } else if (usage > 100) {
            usage = 100;
        }
        var output = new NetworkScope();
        output.setSubnets(IPv4Util.mergeToLargerIfCovered(source.getSubnets(), usage));
        output.setDomains(source.getDomains());
        output.setASN(source.getASN());
        output.setAutoResolvedDomains(source.getAutoResolvedDomains());
        return output;
    }

    private final static Map<String, PropertyDescriptor> properties;

    static {
        properties = new HashMap<>();
        properties.put(USAGE,
                PropertyDescriptor.builder().type(PropertyType.INTEGER).required(true).array(false).defaultValue(75).build()
                        .addConstraint(new IntegerConstraint(51, 99))
        );
    }

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

}
