"""
Test Swfit api.
"""
from cStringIO import StringIO
from configobj import ConfigObj
import base64
import contextlib
import logging
import os

from teuthology import misc as teuthology
from teuthology import contextutil
from ..config import config as teuth_config
from ..orchestra import run
from ..orchestra.connection import split_user

log = logging.getLogger(__name__)


@contextlib.contextmanager
def download(ctx, config):
    """
    Download the Swift API.
    """
    testdir = teuthology.get_testdir(ctx)
    assert isinstance(config, list)
    log.info('Downloading swift...')
    for client in config:
        ctx.cluster.only(client).run(
            args=[
                'git', 'clone',
                teuth_config.ceph_git_base_url + 'swift.git',
                '{tdir}/swift'.format(tdir=testdir),
                ],
            )
    try:
        yield
    finally:
        log.info('Removing swift...')
        testdir = teuthology.get_testdir(ctx)
        for client in config:
            ctx.cluster.only(client).run(
                args=[
                    'rm',
                    '-rf',
                    '{tdir}/swift'.format(tdir=testdir),
                    ],
                )

def _config_user(testswift_conf, account, user, suffix):
    """
    Configure a swift user

    :param account: Swift account
    :param user: User name
    :param suffix: user name and email suffixes.
    """
    testswift_conf['func_test'].setdefault('account{s}'.format(s=suffix), account)
    testswift_conf['func_test'].setdefault('username{s}'.format(s=suffix), user)
    testswift_conf['func_test'].setdefault('email{s}'.format(s=suffix), '{account}+test@test.test'.format(account=account))
    testswift_conf['func_test'].setdefault('display_name{s}'.format(s=suffix), 'Mr. {account} {user}'.format(account=account, user=user))
    testswift_conf['func_test'].setdefault('password{s}'.format(s=suffix), base64.b64encode(os.urandom(40)))

@contextlib.contextmanager