from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager # Flask Login
from os import path

db = SQLAlchemy()
DB_NAME = "database.db"

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'Th15_iS-M1!S3cre4' # used to encrypt session cookies
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    db.init_app(app)

    # import blueprints
    from .logic import logic 

    # register blueprints
    app.register_blueprint(logic, url_prefix  = '/') # allows the setting of prefixes for pages

    # import Database models
    from .models import User, Bookmark, Groups

    create_database(app)

    login_manager = LoginManager()
    # redirect here if not logged in
    login_manager.login_view =  'logic.login' ##'logic.login' 
    login_manager.init_app(app)

    @login_manager.user_loader
    # tells flask how to load a user from the db
    def load_user(id):
        return User.query.get(int(id)) # by default get() looks for the primary key

    return app


def create_database(app):
    if not path.exists('app/' + DB_NAME):
        db.create_all(app=app)
        print('Created Database!')
