import os
import gc
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
from flask_caching import Cache
from flask_sqlalchemy import SQLAlchemy
# from flask_migrate import Migrate
from apscheduler.schedulers.background import BackgroundScheduler
from app.config import configs

db = SQLAlchemy()
cache = Cache()


# def pipeline_runner():
#     new_app = Flask(__name__)
#     config_name = os.getenv('FLASK_ENV') or 'default'
#     new_app.config.from_object(configs[config_name])
#     if new_app.config.get('REPORT_CONFIG_FILE'):
#         with open(new_app.config.get('REPORT_CONFIG_FILE'), 'r', encoding='utf8') as f:
#             new_app.config['REPORT_CONFIG'] = yaml.load(f, SafeLoader)
#             f.close()
#     with new_app.app_context():
#         return transfer_pipeline()


def create_app():
    app = Flask(__name__)

    config_name = os.getenv('FLASK_ENV') or 'default'
    app.config.from_object(configs[config_name])
    db.init_app(app)
    # migrate.init_app(app, db)
    cache.init_app(app)

    from app.main import main as main_blueprint
    app.register_blueprint(main_blueprint)
    with app.app_context():
        db.create_all()

    # if app.config['AUTO_UPDATE']:
    #     sched = BackgroundScheduler(daemon=True)
    #     sched.add_job(pipeline_runner, 'interval', seconds=90)
    #     sched.start()

    if not app.debug and not app.testing:
        if app.config['LOG_TO_STDOUT']:
            stream_handler = logging.StreamHandler()
            stream_handler.setLevel(logging.INFO)
            app.logger.addHandler(stream_handler)
        else:
            if not os.path.exists('logs'):
                os.mkdir('logs')
            file_handler = RotatingFileHandler('logs/reporting.log', maxBytes=10240, backupCount=10)
            file_handler.setFormatter(logging.Formatter(
                '%(asctime)s %(levelname)s: %(message)s '
                '[in %(pathname)s:%(lineno)d]'))
            file_handler.setLevel(logging.INFO)
            app.logger.addHandler(file_handler)

        app.logger.setLevel(logging.INFO)
        app.logger.info('PV Reporting Server Created')

    gc.collect()
    return app
