import importlib


def register_this_deployable(ts, package_info, resources, resource_attributes):
    """
    Registers top level information for a deployable package.

    'package_info' is a dict containing Python package info for current deployable. The dict contains
    at a minimum 'name' and 'description' fields.

    'resources' is a list of resource modules in use by this deployable.

    'resource_attributes' is a dict containing optional attributes for resources. Key is the resource
    module name, value is a dict of any key values attributes which gets passed into registration callback
    functions in the resource modules.

    Returns a dict with 'old_registration' row and 'new_registration' row.
    """
    tbl = ts.get_table('deployable-names')
    pk = {'deployable_name': package_info['name']}
    orig_row = tbl.get(pk)
    if orig_row:
        row = orig_row
        orig_row = orig_row.copy()
    else:
        pk['display_name'] = package_info['description']  # This is a required field
        row = tbl.add(pk)

    row['display_name'] = package_info['description']
    if 'long-description' in package_info and package_info['long-description'] != "UNKNOWN":
        row['description'] = package_info['long-description']
    row['resources'] = resources
    row['resource_attributes'] = resource_attributes

    # Call hooks for top level registration.
    for module_name in row['resources']:
        m = importlib.import_module(module_name)
        if hasattr(m, 'register_deployable'):
            attributes = resource_attributes.setdefault(module_name, {})
            m.register_deployable(
                ts=ts,
                deployablename=row,
                attributes=attributes,
            )

            # For cleanliness, remove resource attribute entry if it's empty
            if not attributes:
                del resource_attributes[module_name]

    return {'old_registration': orig_row, 'new_registration': row}