package ru.kirillius.pf.sdn.flow;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ru.kirillius.pf.sdn.api.Networking.IPv4Subnet;
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.*;
import java.util.regex.Pattern;

@Slf4j
@RequiredArgsConstructor
public class StaticResourceInput extends CommonFunction {

    private final static String SUBNETS = "subnets";
    private final static String DOMAINS = "domains";
    private final static String RESOLVE = "resolve";

    private final static String ASN = "asn";

    private final static Map<String, PropertyDescriptor> properties;

    static {
        properties = new HashMap<>();
        properties.put(SUBNETS, PropertyDescriptor.builder().type(PropertyType.SUBNET).array(true).required(false).defaultValue(null).build());
        properties.put(DOMAINS, PropertyDescriptor.builder().type(PropertyType.STRING).array(true).required(false).defaultValue(null).build());
        properties.put(RESOLVE, PropertyDescriptor.builder().type(PropertyType.STRING).array(true).required(false).defaultValue(null).build());

        properties.put(ASN, PropertyDescriptor.builder().type(PropertyType.INTEGER).array(true).required(false).defaultValue(null).build().addConstraint(new IntegerConstraint(1, 99999))); //TODO какой max asn?);
    }

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

    @Override
    public void apply(CallContext context) {
        var output = new NetworkScope();

        var properties = context.getProperties();

        if (properties.containsKey(SUBNETS)) {
            output.setSubnets(Arrays.stream(properties.get(SUBNETS).split(Pattern.quote(","))).filter(s -> !s.isBlank()).map(IPv4Subnet::new).toList());
        }

        if (properties.containsKey(DOMAINS)) {
            output.setDomains(Arrays.stream(properties.get(DOMAINS).split(Pattern.quote(","))).filter(s -> !s.isBlank()).toList());
        }
        if (properties.containsKey(RESOLVE)) {
            output.setResolveDomains(Arrays.stream(properties.get(RESOLVE).split(Pattern.quote(","))).filter(s -> !s.isBlank()).toList());
        }

        if (properties.containsKey(ASN)) {

            output.setASN(Arrays.stream(properties.get(ASN).split(Pattern.quote(","))).filter(s -> !s.isBlank()).map(Integer::parseInt).toList());
        }

        context.setOutputs(List.of(output));
    }

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

}
