__author__ = 'liam'

from .. import app, db
from ..models import Exam, Problem, Solution, Category, User

from flask.ext.login import current_user
from flask.ext.restless import ProcessingException, APIManager


def allow_all(**kw):
    pass


def allow_user(**kw):
    if not current_user.is_authenticated():
        raise ProcessingException(description='Not Authorized', code=401)


def allow_none(**kw):
    raise ProcessingException(description='Not Authorized', code=401)


@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    return response


exam_preprocessors = {
    'GET_SINGLE': [allow_all],
    'GET_MANY': [allow_all],
    'POST_SINGLE': [allow_user],
    'POST_MANY': [allow_none],
    'PUT_SINGLE': [allow_user],
    'PUT_MANY': [allow_none],
    'DELETE_SINGLE': [allow_user],
    'DELETE_MANY': [allow_none]
}

category_preprocessors = {
    'GET_SINGLE': [allow_all],
    'GET_MANY': [allow_all],
    'POST_SINGLE': [allow_user],
    'POST_MANY': [allow_none],
    'PUT_SINGLE': [allow_user],
    'PUT_MANY': [allow_none],
    'DELETE_SINGLE': [allow_user],
    'DELETE_MANY': [allow_none]
}

problem_preprocessors = {
    'GET_SINGLE': [allow_all],
    'GET_MANY': [allow_all],
    'POST_SINGLE': [allow_user],
    'POST_MANY': [allow_none],
    'PUT_SINGLE': [allow_user],
    'PUT_MANY': [allow_none],
    'DELETE_SINGLE': [allow_user],
    'DELETE_MANY': [allow_none]
}

user_preprocessors = {
    'GET_SINGLE': [allow_all],
    'GET_MANY': [allow_all],
    'POST_SINGLE': [allow_none],
    'POST_MANY': [allow_none],
    'PUT_SINGLE': [allow_none],
    'PUT_MANY': [allow_none],
    'DELETE_SINGLE': [allow_none],
    'DELETE_MANY': [allow_none]
}


apimanager = APIManager(app, flask_sqlalchemy_db=db)


apimanager.create_api(Category, preprocessors=category_preprocessors, methods=['GET', 'PUT', 'POST', 'DELETE'])
apimanager.create_api(Exam, preprocessors=exam_preprocessors, methods=['GET', 'PUT', 'POST', 'DELETE'])
apimanager.create_api(Problem, preprocessors=problem_preprocessors, methods=['GET', 'PUT', 'POST', 'DELETE'])
apimanager.create_api(Solution, preprocessors=problem_preprocessors, methods=['GET', 'PUT', 'POST', 'DELETE'])
