import socket
import errno


def _discovery_multicast(ip: str, sock: socket.socket, attempts: int = 5):
    """
    Send a multicast command on the given network to discover available
        devices.
    If port is in use, try the next port up to <attempts> times

    Args:
        ip (str): Local IP
        sock (socket.socket): Socket object
        attempts (int, optional): Number of times trying different ports
            if port is in use. Defaults to `5`.

    Returns:
        tuple: (sent: bool, port: int) ``sent`` is `True` after sending the
            command. ``port`` is the one used for the connection
    """
    multicast_ip = "239.253.1.1"
    port = 50000
    sent = False
    for i in range(attempts):
        try:
            port += i
            sock.bind((ip, port))
            sock.sendto(b"hdiq-discovery-request-py", (multicast_ip, port))
            sent = True
        except OSError as e:
            if e.errno == errno.EADDRINUSE and i < attempts:
                print(f"Socket Error {errno.EADDRINUSE}: socket in use")
                continue
            break
        else:
            break
    return sent, port