# coding: utf-8
from flask import Flask
from flask.logging import default_handler
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_mail import Mail
from flask_bcrypt import Bcrypt


import logging
import sys
import os


class Config:
	SECRET_KEY = os.environ.get('SECRET_KEY')
	SQLALCHEMY_TRACK_MODIFICATIONS = False
	SQLALCHEMY_ECHO = False
	DEBUG = os.environ.get('DEBUG')
	SESSION_COOKIE_DOMAIN = os.environ.get('COOKIE_DOMAIN')
	SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_WEBDB_URI')

	SQLALCHEMY_BINDS = {
	    'system': os.environ.get('SQLALCHEMY_WEBDB_URI'),
	    'gtfs_work': os.environ.get('SQLALCHEMY_HOTDB_URI'),
	    'gtfs_static': os.environ.get('SQLALCHEMY_GTFSDB_URI'),
		}
	MAIL_DEBUG = int(os.environ.get('DEBUG') == True)
	SQLALCHEMY_ENGINE_OPTIONS = {
		'pool_size': 2,
	    'pool_recycle': 300,
	    'pool_pre_ping': True
		}
#if sys.version_info.major < 3:
#    reload(sys)
#sys.setdefaultencoding('utf8')

bcrypt = Bcrypt()
mail = Mail()

login_manager = LoginManager()
login_manager.login_view = 'main.login'
login_manager.login_message = u'Para continuar, ingrese su nombre de usuario y contraseña.'
login_manager.login_message_category = 'info'

db = SQLAlchemy()

def create_app(config_class=Config):
	app = Flask(__name__)

	app.config.from_object(config_class)

	login_manager.init_app(app)

	if app.debug:
		app.logger.setLevel(logging.DEBUG)
	else:
		app.logger.setLevel(logging.INFO)

	db.init_app(app)

	from webinterface.content.main import main
	app.register_blueprint(main)

	return app
