import logging,traceback,sys
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
#from flask_migrate import Migrate
from flask_login import LoginManager
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
#from flask_babel import Babel, lazy_gettext as _l
#from config import Config
#from app.models import User,Log
from ps.Basic import Basic

db = SQLAlchemy()
#migrate = Migrate()
login = LoginManager()
login.login_view = 'auth.login'
login.login_message = ('Please log in to access this page.')
mail = Mail()
bootstrap = Bootstrap()
moment = Moment()
#babel = Babel()

from dotenv import load_dotenv
from ps.Basic import Basic



basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))


class Config(object):
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
    #SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
    #    'sqlite:///' + os.path.join(basedir, 'app.db')
    #SQLALCHEMY_DATABASE_URI =   Basic.herald_sqlite_filename
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    MAIL_SERVER = os.environ.get('MAIL_SERVER')
    MAIL_PORT = int(os.environ.get('MAIL_PORT') or 25)
    MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS') is not None
    MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
    MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
    ADMINS = ['your-email@example.com']
    LANGUAGES = ['en', 'es']
    #MS_TRANSLATOR_KEY = os.environ.get('MS_TRANSLATOR_KEY')
    POSTS_PER_PAGE = 25


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    if Basic.herald_sqlite_filename == "not_yet_defined":
       ps_basic_singleton = Basic.get_instance("herald")

    if app.config['TESTING'] == True: print("Init for TESTING with ")
    else:
        app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///' + Basic.herald_sqlite_filename
        print("The databasefile will be %s"%(app.config['SQLALCHEMY_DATABASE_URI']))
    
    len = 0
    if  os.path.isfile(Basic.herald_sqlite_filename) :
        statinfo = os.stat(Basic.herald_sqlite_filename)
        len = statinfo.st_size

    db.init_app(app)
    
     
    if not os.path.isfile(Basic.herald_sqlite_filename) or len < 1000:
        with app.app_context():
            try:
                db.create_all()
                
            except:
                db.session.rollback()
                print(traceback.format_exc())
                Basic.logger.exception("error init database")
                sys.exit(1)
            print("The database file %s was initialized"%(app.config['SQLALCHEMY_DATABASE_URI'] ))
    else:
            statinfo = os.stat(Basic.herald_sqlite_filename)
            print("Reuse The database file %s was initialized len is %d "%(app.config['SQLALCHEMY_DATABASE_URI'],statinfo.st_size ))

    login.init_app(app)
    mail.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    #babel.init_app(app)

    from ps_herald.errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    from ps_herald.auth import bp as auth_bp
    app.register_blueprint(auth_bp, url_prefix='/auth')

    from ps_herald.main import bp as main_bp
    app.register_blueprint(main_bp)

    if not app.debug and not app.testing:
        if app.config['MAIL_SERVER']:
            auth = None
            if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
                auth = (app.config['MAIL_USERNAME'],
                        app.config['MAIL_PASSWORD'])
            secure = None
            if app.config['MAIL_USE_TLS']:
                secure = ()
            mail_handler = SMTPHandler(
                mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
                fromaddr='no-reply@' + app.config['MAIL_SERVER'],
                toaddrs=app.config['ADMINS'], subject='Microblog Failure',
                credentials=auth, secure=secure)
            mail_handler.setLevel(logging.ERROR)
            app.logger.addHandler(mail_handler)

        #if not os.path.exists('logs'):
        #    os.mkdir('logs')
        #file_handler = RotatingFileHandler('logs/microblog.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('Microblog startup')
        Basic.logger.info("herald app handler started")

    return app


#@babel.localeselector
#def get_locale():
#    return request.accept_languages.best_match(current_app.config['LANGUAGES'])


from ps_herald import models
