import collections


def _serialize_allocations_for_resource_provider(allocations,
                                                 resource_provider,
                                                 want_version):
    """Turn a list of allocations into a dict by consumer id.

    {'resource_provider_generation': GENERATION,
     'allocations':
       CONSUMER_ID_1: {
           'resources': {
              'DISK_GB': 4,
              'VCPU': 2
           },
           # Generation for consumer >= 1.28
           'consumer_generation': 0
       },
       CONSUMER_ID_2: {
           'resources': {
              'DISK_GB': 6,
              'VCPU': 3
           },
           # Generation for consumer >= 1.28
           'consumer_generation': 0
       }
    }
    """
    show_consumer_gen = want_version.matches((1, 28))
    allocation_data = collections.defaultdict(dict)
    for allocation in allocations:
        key = allocation.consumer.uuid
        if 'resources' not in allocation_data[key]:
            allocation_data[key]['resources'] = {}

        resource_class = allocation.resource_class
        allocation_data[key]['resources'][resource_class] = allocation.used

        if show_consumer_gen:
            consumer_gen = None
            if allocation.consumer is not None:
                consumer_gen = allocation.consumer.generation
            allocation_data[key]['consumer_generation'] = consumer_gen

    result = {'allocations': allocation_data}
    result['resource_provider_generation'] = resource_provider.generation
    return result