import logging
import random
import string
import sys

from oslo.config import cfg

# Logging setup
logger = logging.getLogger(__name__)
stdout = logging.StreamHandler(sys.stdout)
stdout.setLevel(logging.DEBUG)
logger.addHandler(stdout)
logger.setLevel(logging.DEBUG)

default_opts = [
    cfg.StrOpt('working_dir',
               default='/opt/docstack',
               help="The base path to use for docstack."),
]

# Option Definitions
infrastructure_opts = [
    cfg.StrOpt('sql_backend',
               default='mysql',
               choices=['mysql', 'postgresql'],
               help="The sql backend to use."),
    cfg.StrOpt('sql_host',
               default='127.0.0.1',
               help="The host for the sql backend."),
    cfg.StrOpt('sql_user',
               default='mysql',
               help="The user for the sql backend."),
    cfg.StrOpt('sql_password',
               default='',
               help="Password for the sql backend."),
    cfg.StrOpt('queue_backend',
               default='rabbit',
               choices=['rabbit', 'qpid', 'zeromq'],
               help="The shared queue to use."),
    cfg.StrOpt('queue_host',
               default='127.0.0.1',
               help="The host for the queue backend."),
    cfg.StrOpt('queue_user',
               default='rabbit',
               help="The user for the queue backend."),
    cfg.StrOpt('queue_password',
               default='',
               help="Password for the sql backend."),
]


def generate_password(length):
    chars = ''.join([string.lowercase, string.uppercase, "1234567890"])
    choice = random.SystemRandom().choice
    return ''.join((choice(chars) for i in range(length)))


def parse():
    conf = cfg.ConfigOpts()
    conf(project='docstack', prog='docstack')

    # Base options
    conf.register_opts(default_opts)

    # Infrastructure
    infrastructure_group = cfg.OptGroup(name="infrastructure",
                                        title="Infrastructure Services")
    conf.register_group(infrastructure_group)
    conf.register_opts(infrastructure_opts, infrastructure_group)
    # Log it all out
    conf.log_opt_values(logger, logging.INFO)

    return conf
    conf.set_default('sql_password', generate_password(12), 'infrastructure')
    conf.set_default('queue_password', generate_password(12), 'infrastructure')

    conf.reload_config_files()
