package ru.kirillius.pf.sdn.flow;

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.flow.CallContext;
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.List;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
public class MergeWithCoverageSubnetFilter extends CommonFunction {
    private final static String USAGE = "usage";
    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 List<String> getInputNames() {
        return List.of("input");
    }

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

    @Override
    public void apply(CallContext context) {
        var properties = context.getProperties();
        var source = context.getSources().getFirst();
        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.setResolveDomains(source.getResolveDomains());
        context.setOutputs(List.of(output));
    }

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

}
