import os
import uuid
from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_uuid import FlaskUUID

# initializing flask app
app = Flask(__name__)
# configuring sqlalchemy and connecting connection to sqlite3
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') or "sqlite:///token.db"
app.config['SECRET_KEY'] = '12345'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# creating database object
db = SQLAlchemy(app)

# creating migrate object
migrate = Migrate(app, db)

# creating API object
api = Api(app)

# initializing UUID
flask_uuid = FlaskUUID()
flask_uuid.init_app(app)


# creating a table name pin_table which has two columns one id which is primary key and the other pin for all the unique
# that would be generated
class pin_table(db.Model):
    id = db.Column('id', db.Integer, primary_key=True)
    s_n = db.Column(db.String(12), unique=True, nullable=False)
    pin = db.Column(db.String(15), unique=True, nullable=False)

    def __init__(self, pin,s_n):
        self.pin = pin
        self.s_n =s_n



# the class for default resource to be returned when ever a request is made
# a pin is generated by flask uuid, which is changed into an integer by the int function
# and the back into str.the [:15] indexing takes only the first 15 string characters.
# the new code generated is saved into the database using the pin_table object.
# the newly generated pin and id is returned in json format
class Generate(Resource):
    def get(self):
        q =pin_table.query.all()
        s_n = 314159265366+len(q)
        pin = str(int(uuid.uuid4()))[:15]
        db.session.add(pin_table(pin,s_n))
        db.session.commit()
        return jsonify({'s_n': s_n, "pin": pin})

# resource route is defined and bounded to class generate
api.add_resource(Generate, '/')

# class for validating pin and id. the id and pin is to be validated is collected in json format and save in variables
# id and pin respectively. the database is then queried and filtered by the pin provided. the resource returned is 1 if
# a match if found andd 0 if non is found
class validate(Resource):
    def get(self):
        request_data = request.get_json()
        s_n = request_data['s_n']
        pin = request_data['pin']
        pin_q = pin_table.query.filter_by(pin=str(pin)).first()
        s_q = pin_table.query.filter_by(s_n=str(s_n)).first()
        if not request_data or not s_n or not pin:
            return jsonify({"message": "send complete details"})
        if not pin_q or not s_q:
            return "0"
        else:
            return "1"

# resource route is defined and bounded to class validate
api.add_resource(validate, '/valid')

if __name__ == '__main__':
    app.run()
