from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
import logging, sys
from logging.handlers import SMTPHandler
from flask_mail import Mail

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
mail=Mail(app)

if not app.debug:
    if app.config['MAIL_SERVER']:
        auth = None
        secure = None
        mail_handler = SMTPHandler(
                mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
                fromaddr=app.config['FROM_ADDRESS'],
                toaddrs=app.config['ADMINS'], subject='MB failure.',
                credentials=auth, secure=secure)
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)

    if app.config['DC_LOGGING']:
        print('#################### TEST PRINT STDERR DEBUG', file=sys.stderr)
        dclog = logging.StreamHandler(stream=sys.stderr)
        dclog.setLevel(logging.INFO)
        dclog.propagate = False
        app.logger.addHandler(dclog)
        app.logger.info('@@@@@@@@@@@@@@@@@@@@@ TEST LOGGER INFO MESSAGE')


from app import routes, models, errors

