import logging
import logstash_formatter
import requests
import os.path

from data.buildlogs import BuildLogs
from data.userevent import UserEventBuilder


def build_requests_session():
  sess = requests.Session()
  adapter = requests.adapters.HTTPAdapter(pool_connections=100,
                                          pool_maxsize=100)
  sess.mount('http://', adapter)
  sess.mount('https://', adapter)
  return sess


def logs_init_builder(level=logging.DEBUG,
                      formatter=logstash_formatter.LogstashFormatter()):
  @staticmethod
  def init_logs():
    handler = logging.StreamHandler()
    root_logger = logging.getLogger('')
    root_logger.setLevel(level)
    handler.setFormatter(formatter)
    root_logger.addHandler(handler)

  return init_logs

# The set of configuration key names that will be accessible in the client. Since these
# values are set to the frontend, DO NOT PLACE ANY SECRETS OR KEYS in this list.
CLIENT_WHITELIST = ['SERVER_HOSTNAME', 'PREFERRED_URL_SCHEME', 'GITHUB_CLIENT_ID',
                    'GITHUB_LOGIN_CLIENT_ID', 'MIXPANEL_KEY', 'STRIPE_PUBLISHABLE_KEY',
                    'ENTERPRISE_LOGO_URL']


def getFrontendVisibleConfig(config_dict):
  visible_dict = {}
  for name in CLIENT_WHITELIST:
    if name.lower().find('secret') >= 0:
      raise Exception('Cannot whitelist secrets: %s' % name)

    if name in config_dict:
      visible_dict[name] = config_dict.get(name, None)

  return visible_dict


class DefaultConfig(object):
  # Flask config
  SECRET_KEY = 'a36c9d7d-25a9-4d3f-a586-3d2f8dc40a83'
  JSONIFY_PRETTYPRINT_REGULAR = False
  SESSION_COOKIE_SECURE = False

  LOGGING_CONFIG = logs_init_builder(formatter=logging.Formatter())
  SEND_FILE_MAX_AGE_DEFAULT = 0
  POPULATE_DB_TEST_DATA = True
  PREFERRED_URL_SCHEME = 'http'
  SERVER_HOSTNAME = 'localhost:5000'

  # Mail config
  MAIL_SERVER = ''
  MAIL_USE_TLS = True
  MAIL_PORT = 587
  MAIL_USERNAME = ''
  MAIL_PASSWORD = ''
  DEFAULT_MAIL_SENDER = ''
  MAIL_FAIL_SILENTLY = False
  TESTING = True

  # DB config
  DB_URI = 'sqlite:///test/data/test.db'
  DB_CONNECTION_ARGS = {
    'threadlocals': True,
    'autorollback': True,
  }

  @staticmethod
  def create_transaction(db):
    return db.transaction()

  DB_TRANSACTION_FACTORY = create_transaction

  # Data storage
  STORAGE_TYPE = 'LocalStorage'
  STORAGE_PATH = 'test/data/registry'

  # Build logs
  BUILDLOGS = BuildLogs('logs.quay.io') # Change me

  # Real-time user events
  USER_EVENTS = UserEventBuilder('logs.quay.io')

  # Stripe config
  BILLING_TYPE = 'FakeStripe'

  # Userfiles
  USERFILES_TYPE = 'LocalUserfiles'
  USERFILES_PATH = 'test/data/registry/userfiles'

  # Analytics
  ANALYTICS_TYPE = "FakeAnalytics"

  # Github Config
  GITHUB_TOKEN_URL = 'https://github.com/login/oauth/access_token'
  GITHUB_USER_URL = 'https://api.github.com/user'
  GITHUB_USER_EMAILS = GITHUB_USER_URL + '/emails'

  GITHUB_CLIENT_ID = ''
  GITHUB_CLIENT_SECRET = ''

  GITHUB_LOGIN_CLIENT_ID = ''
  GITHUB_LOGIN_CLIENT_SECRET = ''

  # Requests based HTTP client with a large request pool
  HTTPCLIENT = build_requests_session()

  # Status tag config
  STATUS_TAGS = {}
  for tag_name in ['building', 'failed', 'none', 'ready']:
    tag_path = os.path.join('buildstatus', tag_name + '.svg')
    with open(tag_path) as tag_svg:
      STATUS_TAGS[tag_name] = tag_svg.read()

  WEBHOOK_QUEUE_NAME = 'webhook'
  DIFFS_QUEUE_NAME = 'imagediff'
  DOCKERFILE_BUILD_QUEUE_NAME = 'dockerfilebuild'

  # Super user config. Note: This MUST BE an empty list for the default config.
  SUPER_USERS = []

  # Feature Flag: Whether billing is required.
  FEATURE_BILLING = True

  # Feature Flag: Whether user accounts automatically have usage log access.
  FEATURE_USER_LOG_ACCESS = False

  # Feature Flag: Whether GitHub login is supported.
  FEATURE_GITHUB_LOGIN = False

  # Feature flag, whether to enable olark chat
  FEATURE_OLARK_CHAT = False

  # Feature Flag: Whether super users are supported.
  FEATURE_SUPER_USERS = False