"""Get (and convert) URL parameters."""

from flask import abort, request

from .data import measurements


def get_param(key, to=str):
    """Get a parameter from the query string.

    Calls `abort(400)` if the value is the wrong type or missing.
    """
    val = request.args.get(key)
    if val is None:
        abort(400)
    try:
        return to(val)
    except ValueError:
        abort(400)


def meas_type(s):
    """Type converter for valid measurements."""
    val = measurements.get(s)
    if val is not None:
        return val
    raise ValueError(f'bad measurement arg: {s!r}')


def year_type(s):
    """Type converter for valid years."""
    if s.isdigit():
        val = int(s)
        if val in range(10000):
            return val
    raise ValueError(f'bad year arg: {s!r}')