import json
import base64


def build_secret_dockerconfigjson(secret_name, image_registry_auth_infos, obj_labels=None):
    """
    Creates a python dict structure for a 'kubernetes.io/dockerconfigjson' secret (it remains to the caller to send
    the yaml to the server with create()). This method does not use/require oc to be resident
    on the python host.
    :param secret_name: The metadata.name to include
    :param image_registry_auth_infos: An iterable collection of ImageRegistryAuthInfo
    :param obj_labels: Additional labels to include in the resulting secret metadata.
    :return: A python dict of a secret resource.
    """

    if obj_labels is None:
        obj_labels = {}

    auths = {}  # A map of registry urls to a map with a single element called 'auth'

    for ira in image_registry_auth_infos:
        b64_username_password = base64.b64encode('{}:{}'.format(ira.username, ira.password).encode()).decode()
        auths[ira.registry_url] = {
            'auth': b64_username_password
        }

    # this is the content you would see if you cat your dockerconfig json file
    dockerconfig = {
        'auths': auths
    }

    # Lazy load to avoid dragging unnecessary dependencies

    # Next, base64 encode the entire file.
    b64_dockerconfigjson = base64.b64encode(json.dumps(dockerconfig, indent=4).encode()).decode()

    # And stick it into the secret's data
    data = {
        '.dockerconfigjson': b64_dockerconfigjson,
    }

    d = {
        'kind': 'Secret',
        'apiVersion': 'v1',
        'metadata': {
            'name': secret_name,
            'labels': obj_labels,
        },
        'type': 'kubernetes.io/dockerconfigjson',
        'data': data
    }

    return d