import select
import socket
import typing

import anyio

from aioarp import _exceptions as exc

from ._base import SocketInterface


class AsyncStream:

    def __init__(self,
                 interface: str,
                 sock: typing.Optional[SocketInterface] = None
                 ):
        self.sock: SocketInterface
        if not sock:
            self.sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003)) # type: ignore
        else:
            self.sock = sock
        self.sock.bind((interface, 0))

    async def receive_frame(self, timeout: float) -> bytes:
        frame: typing.Optional[bytes]
        with anyio.move_on_after(timeout):
            while True:
                r, _, _ = select.select([self.sock], [], [], 0.00001)
                if r:
                    frame = self.sock.recv(1123123)
                    break
                await anyio.sleep(0)
        if not frame:
            raise exc.ReadTimeoutError()
        return frame
    
    