# Path: _15thnight/forms.py
# class ServiceForm(Form):
#     name = TextField("Name", validators=[DataRequired()])
#     description = TextAreaField("Description")
#     category = SelectField('Category', coerce=int)
# 
#     def __init__(self, *args, **kwargs):
#         super(ServiceForm, self).__init__(*args, **kwargs)
#         self.category.choices = [
#             (category.id, category.name) for category in Category.all()
#         ]
#         self.validate_unique_name = kwargs.get('validate_unique_name', True)
# 
#     def validate_name(self, field):
#         if self.validate_unique_name and Service.get_by_name(field.data):
#             raise ValidationError('This service name is already in use.')
# 
# Path: _15thnight/models.py
# class Service(Model):
#     """Service of provider."""
#     __tablename__ = 'service'
# 
#     id = Column(Integer, primary_key=True)
#     name = Column(String(255), nullable=False, unique=True)
#     description = Column(Text)
#     category_id = Column(ForeignKey('categories.id'), nullable=False)
#     category = relationship(
#         'Category', backref=backref('services', cascade="all, delete-orphan"))
#     sort_order = Column(Integer, nullable=False, default=0)
# 
#     @classmethod
#     def get_by_category(cls, category_id):
#         return cls.query.filter(cls.category_id == category_id) \
#             .order_by(cls.sort_order) \
#             .all()
# 
#     @classmethod
#     def get_by_name(cls, name):
#         return cls.query.filter(cls.name == name).first()
# 
#     def to_json(self):
#         return dict(
#             id=self.id,
#             name=self.name,
#             description=self.description,
#             category=dict(
#                 id=self.category.id,
#                 name=self.category.name,
#                 description=self.category.description
#             ),
#             sort_order=self.sort_order
#         )
# 
# class Category(Model):
#     """Category/type of provided help representation."""
#     __tablename__ = "categories"
# 
#     id = Column(Integer, primary_key=True)
#     name = Column(String(255), nullable=False, unique=True)
#     description = Column(Text)
#     sort_order = Column(Integer, nullable=False, default=0)
# 
#     @classmethod
#     def all(cls):
#         return cls.query.order_by(cls.sort_order).all()
# 
#     @classmethod
#     def get_by_name(cls, name):
#         return cls.query.filter(cls.name == name).first()
# 
#     def to_json(self):
#         return dict(
#             id=self.id,
#             name=self.name,
#             description=self.description,
#             services=Service.get_by_category(self.id),
#             sort_order=self.sort_order
#         )
# 
# Path: _15thnight/util.py
# def required_access(*roles):
#     def templated(f):
#         @wraps(f)
#         def decorated(*args, **kwargs):
#             if current_user.is_anonymous or current_user.role not in roles:
#                 return 'Access Denied.', 403
#             return f(*args, **kwargs)
#         return decorated
#     return templated
# 
# def jsonify(*args, **kwargs):
#     """Returns a json response"""
#     data = None
#     indent = not request.is_xhr
#     status = kwargs.pop('_status_code', 200)
#     if args:
#         data = args[0] if len(args) == 1 else args
#     if kwargs:
#         if data:
#             if type(data) != list:
#                 data = [data]
#             data.append(dict(**kwargs))
#         else:
#             data = dict(**kwargs)
#     return current_app.response_class(
#         dumps(data, indent=indent), status=status, mimetype='application/json'
#     )
# 
# def api_error(message='Bad Request', code=400):
#     return jsonify(error=message, _status_code=code)


from flask import Blueprint, request
from flask.ext.login import login_required
from _15thnight.forms import ServiceForm
from _15thnight.models import Service, Category
from _15thnight.util import required_access, jsonify, api_error

@service_api.route('/<int:service_id>', methods=['GET'])
@required_access('admin')
def get_service(service_id):
    """
    Gets a service.
    """
    return jsonify(Service.get(service_id))


@service_api.route('', methods=['POST'])
@required_access('admin')
def create_service():
    """
    Create a service. Must be an admin.
    """
    form = ServiceForm()
    if not form.validate_on_submit():
        return api_error(form.errors)

    service = Service(
        name=form.name.data,
        description=form.description.data,
        category=Category.get(form.category.data)
    )
    service.save()
    return '', 201


@service_api.route('/<int:service_id>', methods=['PUT'])

# Path: _15thnight/forms.py
# class ServiceForm(Form):
#     name = TextField("Name", validators=[DataRequired()])
#     description = TextAreaField("Description")
#     category = SelectField('Category', coerce=int)
# 
#     def __init__(self, *args, **kwargs):
#         super(ServiceForm, self).__init__(*args, **kwargs)
#         self.category.choices = [
#             (category.id, category.name) for category in Category.all()
#         ]
#         self.validate_unique_name = kwargs.get('validate_unique_name', True)
# 
#     def validate_name(self, field):
#         if self.validate_unique_name and Service.get_by_name(field.data):
#             raise ValidationError('This service name is already in use.')
# 
# Path: _15thnight/models.py
# class Service(Model):
#     """Service of provider."""
#     __tablename__ = 'service'
# 
#     id = Column(Integer, primary_key=True)
#     name = Column(String(255), nullable=False, unique=True)
#     description = Column(Text)
#     category_id = Column(ForeignKey('categories.id'), nullable=False)
#     category = relationship(
#         'Category', backref=backref('services', cascade="all, delete-orphan"))
#     sort_order = Column(Integer, nullable=False, default=0)
# 
#     @classmethod
#     def get_by_category(cls, category_id):
#         return cls.query.filter(cls.category_id == category_id) \
#             .order_by(cls.sort_order) \
#             .all()
# 
#     @classmethod
#     def get_by_name(cls, name):
#         return cls.query.filter(cls.name == name).first()
# 
#     def to_json(self):
#         return dict(
#             id=self.id,
#             name=self.name,
#             description=self.description,
#             category=dict(
#                 id=self.category.id,
#                 name=self.category.name,
#                 description=self.category.description
#             ),
#             sort_order=self.sort_order
#         )
# 
# class Category(Model):
#     """Category/type of provided help representation."""
#     __tablename__ = "categories"
# 
#     id = Column(Integer, primary_key=True)
#     name = Column(String(255), nullable=False, unique=True)
#     description = Column(Text)
#     sort_order = Column(Integer, nullable=False, default=0)
# 
#     @classmethod
#     def all(cls):
#         return cls.query.order_by(cls.sort_order).all()
# 
#     @classmethod
#     def get_by_name(cls, name):
#         return cls.query.filter(cls.name == name).first()
# 
#     def to_json(self):
#         return dict(
#             id=self.id,
#             name=self.name,
#             description=self.description,
#             services=Service.get_by_category(self.id),
#             sort_order=self.sort_order
#         )
# 
# Path: _15thnight/util.py
# def required_access(*roles):
#     def templated(f):
#         @wraps(f)
#         def decorated(*args, **kwargs):
#             if current_user.is_anonymous or current_user.role not in roles:
#                 return 'Access Denied.', 403
#             return f(*args, **kwargs)
#         return decorated
#     return templated
# 
# def jsonify(*args, **kwargs):
#     """Returns a json response"""
#     data = None
#     indent = not request.is_xhr
#     status = kwargs.pop('_status_code', 200)
#     if args:
#         data = args[0] if len(args) == 1 else args
#     if kwargs:
#         if data:
#             if type(data) != list:
#                 data = [data]
#             data.append(dict(**kwargs))
#         else:
#             data = dict(**kwargs)
#     return current_app.response_class(
#         dumps(data, indent=indent), status=status, mimetype='application/json'
#     )
# 
# def api_error(message='Bad Request', code=400):
#     return jsonify(error=message, _status_code=code)


# Path: _15thnight/api/service.py
from flask import Blueprint, request
from flask.ext.login import login_required
from _15thnight.forms import ServiceForm
from _15thnight.models import Service, Category
from _15thnight.util import required_access, jsonify, api_error


@service_api.route('/<int:service_id>', methods=['GET'])
@required_access('admin')
def get_service(service_id):
    """
    Gets a service.
    """
    return jsonify(Service.get(service_id))


@service_api.route('', methods=['POST'])
@required_access('admin')
def create_service():
    """
    Create a service. Must be an admin.
    """
    form = ServiceForm()
    if not form.validate_on_submit():
        return api_error(form.errors)

    service = Service(
        name=form.name.data,
        description=form.description.data,
        category=Category.get(form.category.data)
    )
    service.save()
    return '', 201


@service_api.route('/<int:service_id>', methods=['PUT'])

@required_access('admin')