import json
import os
import sys
# pylint: disable=wrong-import-position,wrong-import-order
import eventlet.tpool
eventlet.tpool.set_num_threads(2)

from munch import munchify
from pathlib import Path

from flask import Flask
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import event
from sqlalchemy import pool
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)

DB_FILE = Path.cwd() / settings.database

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{DB_FILE}"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

# pylint: disable=unused-argument
@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
    """ enables foreign keys on every established connection """
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA foreign_keys=ON")
    cursor.close()

db = SQLAlchemy(app, engine_options=dict(
    poolclass=pool.SingletonThreadPool,
    connect_args=dict(
        check_same_thread=False
        )
    )
)
migrate = Migrate(app, db)
