from oaa.tree_builder import build_tree
from oaaclient.templates import OAAPermission
import petl

CUSTOM_PERMISSIONS = {
    'reader': {
        'permissions': [
            OAAPermission.DataRead
        ],
        'apply_to_sub_resources': True,
        'resource_types': [
            'app'
        ]
    }
}


def run(provider, sources=None, config=None):
    source = sources['apps']

    # create custom permissions for application access

    for permission_name, permission in CUSTOM_PERMISSIONS.items():
        provider.add_custom_permission(permission_name,
                                       permission['permissions'],
                                       apply_to_sub_resources=permission['apply_to_sub_resources'],  # noqa E501
                                       resource_types=permission['resource_types']) # noqa E501
    # self.app.add_local_role("Write", ["Pull", "Fork", "Push", "Merge"])
    provider.add_local_role("AppReader",
                            unique_id='app_reader',
                            permissions=list(CUSTOM_PERMISSIONS.keys()))

    # records = sources['apps'].records
    id_field = source.tree.id_field
    parent_id_field = source.tree.parent_id_field
    sub_fieldname = source.tree.sub_fieldname

    tree = build_tree(source.stream,
                      sub_fieldname=sub_fieldname,
                      id_field=id_field,
                      parent_id_field=parent_id_field)

    for app in petl.records(tree):
        oaa_app = provider.resources[app.app_id]

        for sub_app in app[sub_fieldname]:
            oaa_app.add_sub_resource(name=sub_app.name,
                                     unique_id=sub_app[id_field],
                                     resource_type=source.resource_type)

    return True
