import re
from urllib.parse import urlparse


def is_uri(uri_string: str):
    # good enough test for uri? https://stackoverflow.com/questions/6718633/python-regular-expression-again-match-url
    uri_regex = re.compile(r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", re.MULTILINE | re.UNICODE)
    # this one, is not good enough!!
    # uri_regex = re.compile(r"((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*", re.MULTILINE | re.UNICODE)

    # # extra check for valid top level domain needed for ndff (Toplevel domain is mandatory!)
    # # see: https://ndff.zendesk.com/hc/nl/requests/39562
    domain_part_ok = False
    try:
        domain_part = urlparse(f'{uri_string}').netloc
        # smallest domain I can imagins WITH a top-level domain part is a.nl (4 chars) https://en.wikipedia.org/wiki/Single-letter_second-level_domain
        domain_part_ok = len(domain_part) > 3 and '.' in domain_part and ' ' not in uri_string and '\n' not in uri_string
    except Exception as e:
        pass

    return domain_part_ok and uri_regex.match(f'{uri_string}')


def is_hex(potential_hex_string):
    """
    Test if the argument value could be a hexadecimal string

    In Postgis for example geometries are saved as hexadecimal strings (WKB)

    :param potential_hex_string:
    :return:
    """
    try:
        int(potential_hex_string, 16)
        return True
    except ValueError:
        return False
