import json

from flask import abort, request, views, make_response

from warmsea import db
from warmsea.models import Category

from . import forms


class CategoriesView(views.MethodView):
    """/Categories
    """

    response_headers = {
        "Content-Type": "application/json; charset=utf-8"
    }

    # @auth.permission_required('read')
    def get(self):
        categories = Category.query.order_by(Category.order)
        result = {
            'value': [{
                'id': c.id,
                'name': c.name,
                'slug': c.slug,
                'description': c.description
            } for c in categories]
        }

        response = make_response(
            json.dumps(result, ensure_ascii=False),
            200,
            self.response_headers
        )
        return response

    # @auth.permission_required('add_category')
    def post(self):
        error_message = None
        form = forms.CategoriesAddForm(data=request.get_json())
        if form.validate():
            category = Category()
            category.name = form.name.data
            category.slug = form.slug.data
            category.description = form.description.data or ""
            try:
                db.session.add(category)
                db.session.commit()
            except Exception as ex:
                error_message = str(ex)
                db.session.rollback()
        else:
            error_message = json.dumps(form.errors, ensure_ascii=False)

        if error_message is None:
            response = make_response('', 201, self.response_headers)
        else:
            body = json.dumps({
                'error': {
                    'message': error_message
                }
            })
            response = make_response(body, 400, self.response_headers)

        return response
