import ipaddress as ip
import socket

REQ_SERVICES = {'http': b"GET / HTTP/1.0\r\n\r\n"}

def getLANip() -> ip.IPv4Address:
    try:
        ipaddr = socket.gethostbyname(socket.gethostname())
    except OSError:
        pass
    else:
        return ip.ip_address(ipaddr)


def validateservice(service: str, h: str, b: bytes) -> str:
    """
    splitlines is in case the ASCII/UTF8 response is less than 32 bytes,
    hoping server sends a \r\n
    """
    if not b:  # empty reply
        return None
    # %% non-empty reply
    svc_txt = b.splitlines()[0].decode("utf-8", "ignore")
    # %% optional service validation
    if service and service not in svc_txt.lower():
        return None

    return svc_txt


def netfromaddress(addr: ip.IPv4Address, mask: str = "24") -> ip.IPv4Network:

    if isinstance(addr, ip.IPv4Address):
        net = ip.ip_network(addr.exploded.rsplit(".", 1)[0] + ".0/{}".format(mask))
    elif isinstance(addr, ip.IPv6Address):
        net = ip.ip_network(addr.exploded.rsplit(":", 1)[0] + ":0/{}".format(mask))
    else:
        raise TypeError(addr)
    return net
