"""parsers for complex URL query types"""
__author__      = "Doktor Databaze"

domain_keys = {
    # sortable keys
    'id': lambda x: x['id'],
    'domain_name': lambda x: x['domain_name'],
    'offense_count': lambda x: x['offense_count'],
    'ip_count': lambda x: len(x['geo_data']),
    'time': lambda x: x['results'][-1]['created'],
    'badness': lambda x: x['results'][-1]['badness'],
    # value arrays
    'countries': lambda x: list(map(lambda g: g['country'], x['geo_data'])),
}

# sort string parser
def sort_params(sortstr):
    reverse = sortstr.startswith('-')
    sortstr = sortstr.removeprefix('-')
    return domain_keys.get(sortstr, lambda x: x.id), reverse

# filter operators
filter_ops = {
    'eq': lambda x, y: x == y,
    'ne': lambda x, y: x != y,
    'gt': lambda x, y: x > y,
    'ge': lambda x, y: x >= y,
    'lt': lambda x, y: x < y,
    'le': lambda x, y: x <= y,
    'in': lambda x, y: y in x,
    'ni': lambda x, y: y not in x
}

def try_number(s):
    try:
        return float(s)
    except ValueError:
        return s

# individual filter string parser
def filter_params(filterstr):
    key, op, value = filterstr.split(':')
    return \
        domain_keys.get(key, lambda x: x.id), \
        filter_ops.get(op, lambda x, y: x == y), \
        try_number(value)