from app import db, api
from app.person.models import Person
from flask import Blueprint
from flask import abort
from flask import jsonify
from flask_restful import Resource
from flask_restful import reqparse

person = Blueprint('person', __name__)

parser = reqparse.RequestParser()
parser.add_argument('name', type=str)
parser.add_argument('cpf', type=str)


class PersonApi(Resource):
    def get(self, id=None, page=1):
        if not id:
            persons = Person.query.paginate(page, 10).items
        else:
            persons = [Person.query.get(id)]
        if not persons:
            abort(404)
        res = {}
        for person in persons:
            res[person.id] = {
                'name': person.name,
                'cpf': person.cpf,
            }
        return jsonify(res)

    def post(self):
        args = parser.parse_args()
        name = args['name']
        cpf = args['cpf']
        person = Person(name, cpf)
        db.session.add(person)
        db.session.commit()
        res = {}
        res[person.id] = {
            'name': person.name,
            'cpf': person.cpf,
        }
        return jsonify(res)

    def put(self, id):
        person = Person.query.get(id)
        args = parser.parse_args()
        person.name = args['name']
        person.cpf = args['cpf']
        db.session.commit()
        res = {}
        res[person.id] = {
            'name': person.name,
            'cpf': person.cpf,
        }
        return jsonify(res)

    def delete(self, id):
        person = Person.query.get(id)
        db.session.delete(person)
        db.session.commit()


api.add_resource(
   PersonApi,
   '/api/person/',
   '/api/person/<int:id>',
   '/api/person/<int:id>/<int:page>'
)
