from flask import Flask
from pages import pages
from flask_restful import Api, Resource, reqparse, fields, marshal_with, abort
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
api = Api(app)
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class LicenseModel(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    company = db.Column(db.String(100), nullable=False)
    machineId = db.Column(db.String(100), nullable=False)
    max_activations = db.Column(db.Integer, nullable=False)
    expire_date = db.Column(db.String(100), nullable=False)

    def __repr__(self):
        str = """
        company = {}
        machineId = {}
        max_activations = {}
        expire_date = {}
        """.format(company, machineId, max_activations, expire_date)
        return str

# only create database once
#db.create_all()

license_put_args = reqparse.RequestParser()
license_put_args.add_argument("id", type=int, help="id is required", required=True)
license_put_args.add_argument("company", type=str, help="company is required")
license_put_args.add_argument("machineId", type=str, help="machineId is required")
license_put_args.add_argument("max_activations", type=int, help="max_activations is required")
license_put_args.add_argument("expire_date", type=str, help="expire_date is required")

# define how to serialize a LicenseModel obj
resource_fields = {
    "id" : fields.Integer,
    "company" : fields.String,
    "machineId" : fields.String,
    "max_activations" : fields.Integer,
    "expire_date" : fields.String
}

class License(Resource):

    @marshal_with(resource_fields)
    def get(self):
        args = license_put_args.parse_args()
        result = LicenseModel.query.filter_by(id=args["id"]).first()
        return result

    @marshal_with(resource_fields)
    def put(self):
        args = license_put_args.parse_args()

        existing_lic = LicenseModel.query.filter_by(id=args["id"]).first()

        if existing_lic:
            abort(409, message="License id taken.")

        lic = LicenseModel(
            id=args["id"], 
            company=args["company"], 
            machineId=args["machineId"], 
            max_activations=args["max_activations"], 
            expire_date=args["expire_date"])
        db.session.add(lic)
        db.session.commit()
        return lic, 201

    @marshal_with(resource_fields)
    def patch(self):
        args = license_put_args.parse_args()
        existing_lic = LicenseModel.query.filter_by(id=args["id"]).first()
        if not existing_lic:
            abort(409, message="License does not exist.")
        
        # modify existing_lic ..

        db.session.commit()
        return existing_lic

    def delete(self):
        pass

api.add_resource(License, "/licenses")

app.register_blueprint(pages)

if __name__ == '__main__':
    app.run(debug=True, port=8000)
