from flask_restful import Resource, reqparse
from flask_jwt import jwt_required
import sqlite3
from models.item import ItemModel


class Item(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('price',type=float,required=True,help="This field cannot be blank")
    data = parser.parse_args()
    parser = reqparse.RequestParser()
    parser.add_argument('price',type=float,required=True,help="This field cannot be blank")
    data = parser.parse_args()
    
    @jwt_required()
    def get(self,name):
        item = ItemModel.find_by_name(name)
        
        if item:
            return item.json()
        return {'message':'Item not found'},404
        
    
    def post(self,name):
        
        if ItemModel.find_by_name(name):
            return {'message': 'An item with name %s already exists' % (name)},400
        
        data = Item.parser.parse_args()
        item = ItemModel(name, data['price'])
        try:
            item.insert()
        except:
            return {"message":"an error occurred"},500
            
        return item, 201
    
    
    def delete(self,name):
        item = Item.find_by_name(name)
        if item:
            item.delete_from_db()
        return {'message': 'item has been deleted'}
        
    def put(self,name):
        data = Item.parser.parse_args()

        item = ItemModel.find_by_name(name)
        if item is None:
            item = ItemModel(name, data['price'])
            
        else:
            item.price = data['price']
        item.save_to_db()
        return item.json()
        
        
        
class ItemList(Resource):
    def get(self):
        return {'items': [Item.json() for item in ItemModel.query.all()]}
        
