import logging.handlers
import os
import time
from pathlib import Path

from flask import Flask


def init_logger():
    fmt = logging.Formatter("%(asctime)s %(levelname)s (%(name)s): %(message)s")
    fmt.converter = time.gmtime
    wng_ch = logging.StreamHandler()
    wng_ch.setLevel(logging.DEBUG)
    wng_ch.setFormatter(fmt)

    pth_log = Path("cachub_logging/journal.log")
    pth_log.parent.mkdir(parents=True, exist_ok=True)
    frot = logging.handlers.TimedRotatingFileHandler(pth_log, when="D", interval=1)
    frot.setLevel(logging.DEBUG)
    frot.setFormatter(fmt)

    logger = logging.getLogger("cachub")
    logger.setLevel(logging.DEBUG)
    logger.addHandler(wng_ch)
    logger.addHandler(frot)


def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    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

    init_logger()

    @app.route('/')
    def page_home():
        logger = logging.getLogger("cachub")
        logger.info("Home")
        return 'Hello, World!'

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

    return app
