import json
import sys
import os

from pathlib import Path
from munch import munchify

from flask import Flask
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import event
from sqlalchemy.engine import Engine

print('- Loading settings')
with open('settings.json') as file:
    settings = munchify(json.load(file))


# create projects folder
if not os.path.exists(settings.projects_folder):
    os.mkdir(settings.projects_folder)

app = Flask(__name__)

if "unittest" in sys.modules:
    # creates an in-memory DB
    db_file = ""
else:
    db_file = Path.cwd() / settings.database

app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{db_file}"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA foreign_keys=ON")
    cursor.close()

db = SQLAlchemy(app)
migrate = Migrate(app, db)
