import os
import yaml


APP_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')


class Config(object):
    DEBUG = False
    TESTING = False
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    JWT_SECRET = 'justfordevandtest'
    AVATAR_STORAGE = 'local'
    AVATAR_PATH = os.path.join(APP_ROOT, 'public', 'avatars')
    EMAIL_SENDING = 'local'
    EMAIL_FROM = 'no-reply@opentestdata.org'


class ProdConfig(Config):
    DB_INSTANCE_CONN_NAME = os.environ.get('DB_INSTANCE_CONN_NAME')
    DB_USER = os.environ.get('DB_USER')
    DB_PASS = os.environ.get('DB_PASS')
    DB_NAME = os.environ.get('DB_NAME')
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://%s:%s@/%s?unix_socket=/cloudsql/%s' % (DB_USER, DB_PASS, DB_NAME, DB_INSTANCE_CONN_NAME)
    JWT_SECRET = os.environ.get('JWT_SECRET')
    AVATAR_STORAGE = 'cloud'
    AVATAR_BUCKET = 'otd-avatars'
    EMAIL_SENDING = 'cloud'


class ProdMigrationConfig(Config):

    def __init__(self):
        # this config assumes a local sql connection to cloud sql server
        with open(os.path.join(APP_ROOT, 'app_secrets.yaml')) as secrets_file:
            secrets = yaml.safe_load(secrets_file)['env_variables']
        ProdMigrationConfig.DB_USER = os.environ.get('DB_USER')
        ProdMigrationConfig.DB_PASS = os.environ.get('DB_PASS')
        ProdMigrationConfig.DB_NAME = os.environ.get('DB_NAME')
        ProdMigrationConfig.SQLALCHEMY_DATABASE_URI = 'mysql://%s:%s@%s/%s' % (secrets['DB_USER'], secrets['DB_PASS'], secrets['DB_SERVER'], secrets['DB_NAME'])


class DevConfig(Config):
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = 'mysql://otd_user:otd_pass@localhost/otd_dev'
    AVATAR_PATH = os.path.join(APP_ROOT, 'public_dev', 'avatars')


class TestConfig(Config):
    TESTING = True
    SQLALCHEMY_DATABASE_URI = 'mysql://otd_user:otd_pass@localhost/otd_test'
    AVATAR_PATH = os.path.join(APP_ROOT, 'public_test', 'avatars')


def get_config():
    # if we're in prod, the GAE_ENV var will be set
    if os.environ.get('GAE_ENV') == 'standard':
        return ProdConfig()

    # otherwise we'll be running locally and should look at FLASK_ENV
    env = os.environ.get('FLASK_ENV')
    if env == 'development':
        return DevConfig()
    elif env == 'testing':
        return TestConfig()
    elif env == 'prod_migration':
        return ProdMigrationConfig()

    raise Exception('Could not find config; did you set FLASK_ENV?')
