package ru.kirillius.pf.sdn.pipeline;

import lombok.RequiredArgsConstructor;
import ru.kirillius.pf.sdn.api.Networking.IPv4Subnet;
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.DomainUpdaterService;

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

@RequiredArgsConstructor
public class AutoResolveDomains implements PipelineFunction {

    private final DomainUpdaterService domainCacheService;

    @Override
    public NetworkScope apply(NetworkScope source, Map<String, String> properties) {
        var output = new NetworkScope();
        output.add(source);

        if (properties.containsKey(CLEAR) && properties.get(CLEAR).equals("true")) {
            output.getAutoResolvedDomains().clear();
        }

        source.getAutoResolvedDomains()
                .forEach(domain -> domainCacheService.getActualAddresses(domain)
                        .forEach(address -> output
                                .getSubnets()
                                .add(new IPv4Subnet(address, 32)
                                )
                        )
                );

        return output;
    }

    private final static String CLEAR = "clear";
    private final static Map<String, PropertyDescriptor> properties;

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

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