from typing import Set, Iterable

from django.contrib.auth.models import Permission
from django.utils.translation import gettext_lazy

from perms.models import permissions_together_map


def get_all_linked_permissions(new_permissions: Iterable[str]) -> Set[str]:
    """Return update set permissions with included permissions"""
    all_permissions: set = {*new_permissions}

    for permission in new_permissions:
        together = permissions_together_map.get(permission)
        if together is None:
            continue
        all_permissions |= together
    return all_permissions


def get_linked_permissions_name(permissions_codename: list) -> dict:
    """Return mapping permissions name with linked permissions name with unique names"""
    permissions = Permission.objects.filter(codename__in=permissions_codename)
    permissions_map = {permission.codename: str(gettext_lazy(permission.name)) for permission in permissions}

    used_permissions = set(permissions_codename)

    linked_permissions_name = {}
    for permission in permissions_codename:
        linked_permission_codenames = permissions_together_map.get(permission, set())
        permissions_for_adding: set = linked_permission_codenames - used_permissions
        used_permissions.update(linked_permission_codenames)
        linked_permissions = map(lambda x: str(gettext_lazy(x)), Permission.objects.filter(codename__in=permissions_for_adding).values_list('name', flat=True))
        linked_permissions_name[permissions_map.get(permission)] = ', '.join(linked_permissions)
    return linked_permissions_name
