# Path: core/validation/permissions.py
# def check_datamine_permissions(action, document):
#     # Get datamine permissions
#     
#     try:
#         restrictions = cherrypy.session['_ts_user']['restrictions'][action]
#     except (KeyError, TypeError):
#         restrictions = None
#         
#     if not restrictions:
#         raise TSValidationError("Access to '%s' is restricted for current user" % (action))
#     elif restrictions != True:
#         validator(restrictions, format_checker=jsonschema.FormatChecker()).validate(document)
# 
# Path: core/validation/validation.py
# class TSValidationError(Exception):
#     pass
# 
# def validate_request(collection, json_in):
#     validator(requests_schema[collection], format_checker=jsonschema.FormatChecker()).validate(json_in)
# 
# def update_password_salt_user_list(collection, list_in):
#     
#     if collection == 'user':
#         for json_in in list_in:
#             update_password_salt_user_json(json_in)
#         
#     return list_in
# 
# def validate_json_list(collection, list_in):
#     
#     for json_in in list_in:    
#         # Validate json schema
#         validator(schema[collection], format_checker=jsonschema.FormatChecker()).validate(json_in)
# 
# def sanitize_objectify_json(json_in):
#     """Sanitize string and convert _ids to ObjectId in JSON"""
#     return recursive_replace(json_in, _replace_function_sanitize_objectify_json)
# 
# def stringify_objectid_cursor(cursor_in):
#     """Convert ObjectId to string in JSON"""
#     
#     stringified = []
#     for json_in in cursor_in:
#         stringified.append(recursive_replace(json_in, _replace_function_stringify_objectid_json))
#     return stringified
# 
# def stringify_objectid_list(list_in):
#     """Convert an ObjectId list to string list"""
#     return recursive_replace(list_in, _replace_function_stringify_objectid_list)
# 
# Path: core/api/crud.py
# def get(collection, criteria_projection_order):
# def remove(collection, criterias = []):
# def add(collection, documents_list):
# def update(collection, document):


from core.validation.permissions import check_datamine_permissions
from core.validation.validation import TSValidationError, validate_request, update_password_salt_user_list, validate_json_list, sanitize_objectify_json, stringify_objectid_cursor, stringify_objectid_list
from bson.objectid import ObjectId
from core.api.crud import db
import cherrypy, logging
    validate_json_list('day', documents_list)
    for document in documents_list:
        check_datamine_permissions('push_days', document)

    sanified_documents_list = sanitize_objectify_json(documents_list)
    
    for sanified_document in sanified_documents_list:

        date = sanified_document['date']
        
        found = db.day.find({ 'date' : date }).limit(1).count()

        users = sanified_document.get('users', [])

        # Validate one user per day insertion
        if len(users) > 1:
            raise TSValidationError("Push only one user per day")

        # If the date is already present and an user is specified
        if found and users:
                                     
            user_id = users[0]['user_id']
            
            # Drop old user data
            db.day.update({'date': date }, {'$pull': {'users': {'user_id': user_id }}})
            # Push new one
            db.day.update({'date': date }, {'$push': {'users': {'user_id': user_id, 'hours' : users[0]['hours'] }}})
        
        # If the data does not already exist and there are new users data, insert it
        elif not found and users:

# Path: core/validation/permissions.py
# def check_datamine_permissions(action, document):
#     # Get datamine permissions
#     
#     try:
#         restrictions = cherrypy.session['_ts_user']['restrictions'][action]
#     except (KeyError, TypeError):
#         restrictions = None
#         
#     if not restrictions:
#         raise TSValidationError("Access to '%s' is restricted for current user" % (action))
#     elif restrictions != True:
#         validator(restrictions, format_checker=jsonschema.FormatChecker()).validate(document)
# 
# Path: core/validation/validation.py
# class TSValidationError(Exception):
#     pass
# 
# def validate_request(collection, json_in):
#     validator(requests_schema[collection], format_checker=jsonschema.FormatChecker()).validate(json_in)
# 
# def update_password_salt_user_list(collection, list_in):
#     
#     if collection == 'user':
#         for json_in in list_in:
#             update_password_salt_user_json(json_in)
#         
#     return list_in
# 
# def validate_json_list(collection, list_in):
#     
#     for json_in in list_in:    
#         # Validate json schema
#         validator(schema[collection], format_checker=jsonschema.FormatChecker()).validate(json_in)
# 
# def sanitize_objectify_json(json_in):
#     """Sanitize string and convert _ids to ObjectId in JSON"""
#     return recursive_replace(json_in, _replace_function_sanitize_objectify_json)
# 
# def stringify_objectid_cursor(cursor_in):
#     """Convert ObjectId to string in JSON"""
#     
#     stringified = []
#     for json_in in cursor_in:
#         stringified.append(recursive_replace(json_in, _replace_function_stringify_objectid_json))
#     return stringified
# 
# def stringify_objectid_list(list_in):
#     """Convert an ObjectId list to string list"""
#     return recursive_replace(list_in, _replace_function_stringify_objectid_list)
# 
# Path: core/api/crud.py
# def get(collection, criteria_projection_order):
# def remove(collection, criterias = []):
# def add(collection, documents_list):
# def update(collection, document):


# Path: core/api/days.py
from core.validation.permissions import check_datamine_permissions
from core.validation.validation import TSValidationError, validate_request, update_password_salt_user_list, validate_json_list, sanitize_objectify_json, stringify_objectid_cursor, stringify_objectid_list
from bson.objectid import ObjectId
from core.api.crud import db
import cherrypy, logging

    validate_json_list('day', documents_list)
    for document in documents_list:
        check_datamine_permissions('push_days', document)

    sanified_documents_list = sanitize_objectify_json(documents_list)
    
    for sanified_document in sanified_documents_list:

        date = sanified_document['date']
        
        found = db.day.find({ 'date' : date }).limit(1).count()

        users = sanified_document.get('users', [])

        # Validate one user per day insertion
        if len(users) > 1:
            raise TSValidationError("Push only one user per day")

        # If the date is already present and an user is specified
        if found and users:
                                     
            user_id = users[0]['user_id']
            
            # Drop old user data
            db.day.update({'date': date }, {'$pull': {'users': {'user_id': user_id }}})
            # Push new one
            db.day.update({'date': date }, {'$push': {'users': {'user_id': user_id, 'hours' : users[0]['hours'] }}})
        
        # If the data does not already exist and there are new users data, insert it
        elif not found and users:

            db.day.insert(sanified_document)