import os, logging
from logging.handlers import RotatingFileHandler

from flask import Flask
from flask_restful import Api


api = Api()


def create_app(test_config=None):
    """ Application factory function.

    Creates and configures the flask app.
    """

    from . import default_configuration
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(default_configuration)

    if test_config is None:
        # Load the instance config, if it exists, when not testing
        app.config.from_envvar('LUMI_CONFIG', 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

    # Set up logging
    if not app.config['DEBUG']:
        app.logger = logging.getLogger('lumi2')
        app.logger.setLevel(logging.INFO)
        app.logger.propagate = False

        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        app.logger.addHandler(console_handler)

        if 'LOG_FILE_PATH' in app.config:
            file_handler = RotatingFileHandler(
                app.config['LOG_FILE_PATH'],
                maxBytes=app.config['LOG_FILE_MAX_SIZE'],
                backupCount=1,
            )
            file_handler.setLevel(logging.INFO)
            app.logger.addHandler(file_handler)

    from lumi2.logging import log_request
    app.after_request(log_request)

    from . import auth
    app.register_blueprint(auth.bp)

    from . import usermanager
    app.register_blueprint(usermanager.bp)
    app.add_url_rule('/', endpoint='index')

    from . import webapi
    api.add_resource(webapi.UserResource, '/api/user/<string:username>')
    api.add_resource(webapi.GroupResource, '/api/group/<string:groupname>')
    api.add_resource(webapi.GroupMemberResource, '/api/group/<string:groupname>/member/<string:username>')
    api.init_app(app)

    return app
