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


# 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', 'SENTRY_PUBLIC_DSN', 'AUTHENTICATION_TYPE',
                    'REGISTRY_TITLE', 'REGISTRY_TITLE_SHORT', 'GOOGLE_LOGIN_CLIENT_ID']


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_LEVEL = 'DEBUG'
  SEND_FILE_MAX_AGE_DEFAULT = 0
  POPULATE_DB_TEST_DATA = True
  PREFERRED_URL_SCHEME = 'http'
  SERVER_HOSTNAME = 'localhost:5000'

  REGISTRY_TITLE = 'Quay.io'
  REGISTRY_TITLE_SHORT = 'Quay.io'

  # Mail config
  MAIL_SERVER = ''
  MAIL_USE_TLS = True
  MAIL_PORT = 587
  MAIL_USERNAME = ''
  MAIL_PASSWORD = ''
  MAIL_DEFAULT_SENDER = 'support@quay.io'
  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

  # If true, CDN URLs will be used for our external dependencies, rather than the local
  # copies.
  USE_CDN = True

  # Authentication
  AUTHENTICATION_TYPE = 'Database'

  # Build logs
  BUILDLOGS_REDIS = {'host': 'localhost'}
  BUILDLOGS_OPTIONS = []

  # Real-time user events
  USER_EVENTS_REDIS = {'host': 'localhost'}

  # Stripe config
  BILLING_TYPE = 'FakeStripe'

  # Analytics
  ANALYTICS_TYPE = 'FakeAnalytics'

  # Build Queue Metrics
  QUEUE_METRICS_TYPE = 'Null'

  # Exception logging
  EXCEPTION_LOG_TYPE = 'FakeSentry'
  SENTRY_DSN = None
  SENTRY_PUBLIC_DSN = None

  # 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 = ''

  # Google Config.
  GOOGLE_TOKEN_URL = 'https://accounts.google.com/o/oauth2/token'
  GOOGLE_USER_URL = 'https://www.googleapis.com/oauth2/v1/userinfo'

  GOOGLE_LOGIN_CLIENT_ID = ''
  GOOGLE_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()

  NOTIFICATION_QUEUE_NAME = 'notification'
  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 = False

  # 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 Google login is supported.
  FEATURE_GOOGLE_LOGIN = False

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

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

  # Feature Flag: Whether to support GitHub build triggers.
  FEATURE_GITHUB_BUILD = False

  # Feature Flag: Dockerfile build support.
  FEATURE_BUILD_SUPPORT = True

  # Feature Flag: Whether emails are enabled.
  FEATURE_MAILING = True

  # Feature Flag: Whether users can be created (by non-super users).
  FEATURE_USER_CREATION = True

  DISTRIBUTED_STORAGE_CONFIG = {
    'local_eu': ['LocalStorage', {'storage_path': 'test/data/registry/eu'}],
    'local_us': ['LocalStorage', {'storage_path': 'test/data/registry/us'}],
  }

  DISTRIBUTED_STORAGE_PREFERENCE = ['local_us']

  # Userfiles
  USERFILES_LOCATION = 'local_us'
  USERFILES_PATH = 'userfiles/'

  # Build logs archive
  LOG_ARCHIVE_LOCATION = 'local_us'
  LOG_ARCHIVE_PATH = 'logarchive/'
