package ru.kirillius.pf.sdn.core.Networking;

import ru.kirillius.pf.sdn.core.AppService;
import ru.kirillius.pf.sdn.core.Context;
import ru.kirillius.pf.sdn.core.Util.DomainUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ResolverService extends AppService {
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private final static String CTX = ResolverService.class.getSimpleName();

    public Future<List<IPv4Subnet>> resolve(String host) {
        return executor.submit(() -> {
            var resolved = new ArrayList<IPv4Subnet>();
            for (var domainResolver : context.getConfig().getDomainResolvers()) {
                DomainUtil.lookup(host, domainResolver).stream().map(addr -> new IPv4Subnet(addr, 32)).forEach(resolved::add);
            }
            return resolved;
        });
    }

    public ResolverService(Context context) {
        super(context);
    }

    /**
     * Removes event subscriptions and shuts down the executor.
     */
    @Override
    public void close() throws IOException {
        executor.shutdown();
    }
}
