package be.fgov.ehealth.technicalconnector.tests.utils;

import be.ehealth.technicalconnector.utils.ConnectorIOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ServerSocket;

public class PortUtils {
    private static final Logger LOG = LoggerFactory.getLogger(PortUtils.class);

    private static final int MAGIC_10000 = 10000;

    public static int getFreePort() {
        int freePort = randomPort();

        while (!freePort(freePort)) {
            freePort = randomPort();
        }
        return freePort;
    }

    public static int randomPort() {
        return (int) (MAGIC_10000 + Math.round(Math.random() * MAGIC_10000));
    }

    public static boolean freePort(int freePort) {
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(freePort);
            freePort = ss.getLocalPort();
            return true;
        } catch (IOException e) {
            LOG.debug("Unable to open port " + freePort, e);
        } finally {
            ConnectorIOUtils.closeQuietly(ss);
        }
        return false;
    }
}
