from django.contrib.auth.models import Permission

from wagtail_global_settings.models import AbstractGlobalSettingsCollection,\
    AbstractSiteSettingsCollection


def user_can_edit_global_settings_type(user, content_type):
    """ true if user has any permission related to this content type """
    if user.is_active and user.is_superuser:
        return True

    permission_codenames = content_type.permission_set.values_list('codename', flat=True)
    for codename in permission_codenames:
        permission_name = "%s.%s" % (content_type.app_label, codename)
        if user.has_perm(permission_name):
            return True

    return False

def user_can_edit_global_settings(user):
    """ true if user has any permission related to any content type registered as a global settings type """
    global_settings_content_types = AbstractGlobalSettingsCollection.get_global_settings_content_types()
    if user.is_active and user.is_superuser:
        # admin can edit global settings if any global settings types exist
        return bool(global_settings_content_types)

    permissions = Permission.objects.filter(content_type__in=global_settings_content_types).select_related('content_type')
    for perm in permissions:
        permission_name = "%s.%s" % (perm.content_type.app_label, perm.codename)
        if user.has_perm(permission_name):
            return True

    return False

def user_can_edit_site_settings(user):
    """ true if user has any permission related to any content type registered as a site settings type """
    site_settings_content_types = AbstractSiteSettingsCollection.get_global_settings_content_types()
    if user.is_active and user.is_superuser:
        # admin can edit global settings if any global settings types exist
        return bool(site_settings_content_types)

    permissions = Permission.objects.filter(content_type__in=site_settings_content_types).select_related('content_type')
    for perm in permissions:
        permission_name = "%s.%s" % (perm.content_type.app_label, perm.codename)
        if user.has_perm(permission_name):
            return True

    return False