from flask_restful import reqparse, abort, Resource, marshal_with, fields
from . import db_session
from recources.Model.Category import Category
from flask import jsonify


def abort_if_user_not_found(category_id):
    db_sess = db_session.create_session()
    user = db_sess.query(Category).get(category_id)
    if not user:
        abort(404, message=f'Category {category_id} not found')


parser = reqparse.RequestParser()
parser.add_argument('name', required=True)


class CategoryResource(Resource):
    def get(self, category_id):
        abort_if_user_not_found(category_id)
        db_sess = db_session.create_session()
        category = db_sess.query(Category).get(category_id)
        return jsonify(
            {'category': category.to_dict()}
        )

    def delete(self, category_id):
        abort_if_user_not_found(category_id)
        db_sess = db_session.create_session()
        category = db_sess.query(Category).get(category_id)
        db_sess.delete(category)
        db_sess.commit()
        return jsonify({'success': 'OK'})

    def put(self, category_id):
        abort_if_user_not_found(category_id)
        args = parser.parse_args()
        db_sess = db_session.create_session()

        category = db_sess.query(Category).get(category_id)
        category.name = args["name"]

        db_sess.commit()

        return jsonify({'success': 'OK'})


class CategoryListResource(Resource):
    def get(self):
        session = db_session.create_session()
        categories = session.query(Category).all()
        return jsonify([item.to_dict() for item in categories])

    def post(self):
        args = parser.parse_args()
        db_sess = db_session.create_session()

        category = Category()
        category.name = args["name"]

        db_sess.add(category)
        db_sess.commit()

        return jsonify({'success': 'OK'})