# Path: habitat/views/utils.py
# def read_json_schema(schemaname):
#     mypath = os.path.dirname(inspect.getfile(inspect.currentframe()))
#     path = os.path.join(mypath, "..", "..", "couchdb", "schemas", schemaname)
#     with open(path) as f:
#         schema = json.load(f)
#     return schema
# 
# def validate_doc(data, schema):
#     """Validate *data* against *schema*, raising descriptive errors"""
#     v = Validator()
#     errors = list(v.iter_errors(data, schema))
#     if errors:
#         errors = ', '.join((str(error) for error in errors))
#         raise ForbiddenError("Validation errors: {0}".format(errors))
#     _validate_formats(data, schema) 
# 
# def must_be_admin(user,
#                   msg="Only server administrators may edit this document."):
#     """Raise UnauthorizedError if the user is not an admin"""
#     try:
#         if '_admin' not in user['roles']:
#             raise UnauthorizedError(msg)
#     except (KeyError, TypeError):
#         raise UnauthorizedError(msg)
# 
# Path: habitat/views/utils.py
# def only_validates(doc_type):
#     def decorator(func):
#         def wrapped(new, old, userctx, secobj):
#             new_type = new.get("type", None)
#             new_deleted = new.get("_deleted", False)
#             if old:
#                 old_type = old.get("type", None)
#             else:
#                 old_type = None
# 
#             # sanity checks
#             if old_type is None:
#                 assert old == {} or old is None
#             if new_deleted:
#                 assert new_type is None
# 
#             if new_type == doc_type and old_type in [None, doc_type]:
#                 # new doc, or modified doc of correct type. validate:
#                 return func(new, old, userctx, secobj)
# 
#             elif new_deleted and old_type == doc_type:
#                 # deletion is managed by habitat.validate
#                 return
# 
#             elif new_type == doc_type or old_type == doc_type:
#                 # one or the other types match but not both, and not a new or deleted doc.
#                 raise ForbiddenError("You cannot change the type of a doc")
# 
#             else:
#                 # other type: not our business
#                 return
# 
#         # Be a well behaved decorator!
#         wrapped.__name__ = func.__name__
#         wrapped.__doc__ = func.__doc__
#         wrapped.__dict__.update(func.__dict__)
# 
#         return wrapped
#     return decorator


from couch_named_python import ForbiddenError, version
from strict_rfc3339 import rfc3339_to_timestamp
from .utils import read_json_schema, validate_doc, must_be_admin
from .utils import only_validates
    for k in required_keys[f['type']]:
        if k not in f:
            raise ForbiddenError(
                "{0} filters must include '{1}'.".format(f['type'], k))

@version(1)
@only_validates("payload_configuration")
def validate(new, old, userctx, secobj):
    """
    Validate payload_configuration documents against the schema and then
    against specific validation requirements.

    * Must match schema
    * If editing, must be an administrator
    * If there are any sentences with protocol=UKHAS:
        * Checksum must be a valid type if provided
        * Must have at least one field
        * Coordinate fields must have a format
    * If any sentences have filters:
        * Normal filters must specify a filter path
        * Hotfix filters must specify code, a signature and a certificate
    * If any transmissions have modulation=RTTY:
        * Must also specify shift, encoding, baud, parity and stop.

    """
    if old:
        must_be_admin(userctx)

    global schema
    if not schema:

# Path: habitat/views/utils.py
# def read_json_schema(schemaname):
#     mypath = os.path.dirname(inspect.getfile(inspect.currentframe()))
#     path = os.path.join(mypath, "..", "..", "couchdb", "schemas", schemaname)
#     with open(path) as f:
#         schema = json.load(f)
#     return schema
# 
# def validate_doc(data, schema):
#     """Validate *data* against *schema*, raising descriptive errors"""
#     v = Validator()
#     errors = list(v.iter_errors(data, schema))
#     if errors:
#         errors = ', '.join((str(error) for error in errors))
#         raise ForbiddenError("Validation errors: {0}".format(errors))
#     _validate_formats(data, schema) 
# 
# def must_be_admin(user,
#                   msg="Only server administrators may edit this document."):
#     """Raise UnauthorizedError if the user is not an admin"""
#     try:
#         if '_admin' not in user['roles']:
#             raise UnauthorizedError(msg)
#     except (KeyError, TypeError):
#         raise UnauthorizedError(msg)
# 
# Path: habitat/views/utils.py
# def only_validates(doc_type):
#     def decorator(func):
#         def wrapped(new, old, userctx, secobj):
#             new_type = new.get("type", None)
#             new_deleted = new.get("_deleted", False)
#             if old:
#                 old_type = old.get("type", None)
#             else:
#                 old_type = None
# 
#             # sanity checks
#             if old_type is None:
#                 assert old == {} or old is None
#             if new_deleted:
#                 assert new_type is None
# 
#             if new_type == doc_type and old_type in [None, doc_type]:
#                 # new doc, or modified doc of correct type. validate:
#                 return func(new, old, userctx, secobj)
# 
#             elif new_deleted and old_type == doc_type:
#                 # deletion is managed by habitat.validate
#                 return
# 
#             elif new_type == doc_type or old_type == doc_type:
#                 # one or the other types match but not both, and not a new or deleted doc.
#                 raise ForbiddenError("You cannot change the type of a doc")
# 
#             else:
#                 # other type: not our business
#                 return
# 
#         # Be a well behaved decorator!
#         wrapped.__name__ = func.__name__
#         wrapped.__doc__ = func.__doc__
#         wrapped.__dict__.update(func.__dict__)
# 
#         return wrapped
#     return decorator


# Path: habitat/views/payload_configuration.py
from couch_named_python import ForbiddenError, version
from strict_rfc3339 import rfc3339_to_timestamp
from .utils import read_json_schema, validate_doc, must_be_admin
from .utils import only_validates

    for k in required_keys[f['type']]:
        if k not in f:
            raise ForbiddenError(
                "{0} filters must include '{1}'.".format(f['type'], k))

@version(1)
@only_validates("payload_configuration")
def validate(new, old, userctx, secobj):
    """
    Validate payload_configuration documents against the schema and then
    against specific validation requirements.

    * Must match schema
    * If editing, must be an administrator
    * If there are any sentences with protocol=UKHAS:
        * Checksum must be a valid type if provided
        * Must have at least one field
        * Coordinate fields must have a format
    * If any sentences have filters:
        * Normal filters must specify a filter path
        * Hotfix filters must specify code, a signature and a certificate
    * If any transmissions have modulation=RTTY:
        * Must also specify shift, encoding, baud, parity and stop.

    """
    if old:
        must_be_admin(userctx)

    global schema
    if not schema:

        schema = read_json_schema("payload_configuration.json")