from flask import request
from flask.ext.restful import abort, Resource

from bdqdb import api, db, models


class Root(Resource):

    def get(self):
        return [t.to_json() for t in models.Tag.query.all()]


class Tag(Resource):

    def get(self, tag):
        t = models.Tag.query.filter_by(name=tag).first()
        if t is None:
	    abort(404)

        return [q.to_json() for q in t.quotes]

    def post(self, tag):
        payload = request.get_json()
        text = payload.get('text', None)
        if text is None:
            abort(400)

        t = models.Tag.query.filter_by(name=tag).first()
        if t is None:
            t = models.Tag(tag)
            db.session.add(t)
            db.session.commit()

        quote = models.Quote(t.id, text)
        db.session.add(quote)
        db.session.commit()
        return quote.to_json(), 201


class TagWithId(Resource):

    def get(self, tag, qid):
	t = models.Tag.query.filter_by(name=tag).first()
        if t is None:
            abort(404)

        for q in t.quotes:
            if q.id_within_tag == qid:
                return q.to_json()

        abort(404)

    def delete(self, tag, qid):
        t = models.Tag.query.filter_by(name=tag).first()
        if t is None:
            abort(404)

        for q in t.quotes:
            if q.id_within_tag == qid:
                db.session.delete(q)
                if t.quotes.count() == 1:
                    db.session.delete(t)
                db.session.commit()
                return

        abort(404)


api.add_resource(Root, '/')
api.add_resource(Tag, '/<string:tag>')
api.add_resource(TagWithId, '/<string:tag>/<int:qid>')

@@ -332,16 +332,59 @@
 s None:%0A
+            msg = 'Tag %25s not found' %25 tag%0A
 %09    abo
@@ -381,32 +381,45 @@
 g%0A%09    abort(404
+, message=msg
 )%0A%0A        retur
@@ -1037,32 +1037,75 @@
   if t is None:%0A
+            msg = 'Tag %25s not found' %25 tag%0A
             abor
@@ -1101,32 +1101,45 @@
        abort(404
+, message=msg
 )%0A%0A        for q
@@ -1223,24 +1223,90 @@
 .to_json()%0A%0A
+        msg = 'No quote with id %25d found for tag %25s' %25 (qid, tag)%0A
         abor
@@ -1306,24 +1306,37 @@
    abort(404
+, message=msg
 )%0A%0A    def d
@@ -1429,32 +1429,75 @@
   if t is None:%0A
+            msg = 'Tag %25s not found' %25 tag%0A
             abor
@@ -1501,16 +1501,29 @@
 bort(404
+, message=msg
 )%0A%0A     
@@ -1763,16 +1763,82 @@
 return%0A%0A
+        msg = 'No quote with id %25d found for tag %25s' %25 (qid, tag)%0A
         
@@ -1846,16 +1846,29 @@
 bort(404
+, message=msg
 )%0A%0A%0Aapi.

Improve error messages