from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import json
from settings import app

db=SQLAlchemy(app)

class Book(db.Model):
	__tablename__='books'
	id=db.Column(db.Integer, primary_key=True)
	name=db.Column(db.String(80), nullable=False)
	price=db.Column(db.Float , nullable=False)
	isbn=db.Column(db.Integer)

	def json(self):
		return {'name': self.name , 'price': self.price, 'isbn': self.isbn} 

	def addBook(_name, _price, _isbn):
		new_book=Book(name=_name, price=_price, isbn=_isbn)
		db.session.add(new_book)
		db.session.commit()

	def getAllBooks():
		return [Book.json(book) for book in Book.query.all()]

	def getBook(_isbn):
		return Book.json(Book.query.filter_by(isbn=_isbn).first())

	def deleteBook(_isbn):
		is_successful=Book.query.filter_by(isbn=_isbn).delete()
		db.session.commit()
		return bool(is_successful)

	def updateBookPrice(_isbn, _price):
		book_to_update=Book.query.filter_by(isbn=_isbn).first()
		book_to_update.price=_price
		db.session.commit()

	def updateBookName(_isbn, _name):
		book_to_update=Book.query.filter_by(isbn=_isbn).first()
		book_to_update.name=_name
		db.session.commit()

	def replaceBook(_isbn, _name, _price):
		book_to_replace=Book.query.filter_by(isbn=_isbn).first()
		book_to_replace.price= _price
		book_to_replace.name= _name
		db.session.commit()


	def __repr__(self):
		book_object={
			'name': self.name,
			'price': self.price,
			'isbn': self.isbn
		}
		return json.dumps(book_object)

