import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_socketio import SocketIO, emit

db = SQLAlchemy()
socketio = SocketIO()


# https://flask.palletsprojects.com/en/1.1.x/tutorial/factory/
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile("config.py", silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # initialize db
    db.init_app(app)

    # initialize SocketIO
    socketio.init_app(app, cors_allowed_origins="*")

    # sock.init_app(app)

    # import routes
    # import commands
    # must be done after db initialization
    with app.app_context():
        from .routes import kds_route
        from .services import kds_service

        # register routes
        app.register_blueprint(kds_route.bp)
        # register services
        app.register_blueprint(kds_service.bp)

        return app
