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.AutonomousSystemCacheService;

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

@RequiredArgsConstructor
public class AutoResolveASN extends CommonFunction {

    private final AutonomousSystemCacheService autonomousSystemCacheService;
    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 void apply(CallContext context) {
        var output = new NetworkScope();
        output.add(context.getSources().getFirst());
        var properties = context.getProperties();

        if (properties.containsKey(CLEAR) && properties.get(CLEAR).equals(Boolean.TRUE.toString())) {
            output.getASN().clear();
        }

        context.getSources().getFirst().getASN().forEach(asn -> output.getSubnets().addAll(autonomousSystemCacheService.load(asn)));
        context.setOutputs(List.of(output));
    }

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

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

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