# coding: utf-8


from django.contrib.admin import site, ModelAdmin
from django.utils.translation import ugettext_lazy as _

from idm.framework.base_admin import IdmModelAdminMixin
from idm.inconsistencies.models import Inconsistency


class InconsistencyModelAdmin(IdmModelAdminMixin, ModelAdmin):
    """
    Неконсистентности в системах
    """
    def resolve_inconsistencies(self, request, queryset):
        resolved = errors = 0
        for inconsistency in queryset:
            try:
                inconsistency.resolve(request.user, force=True)
            except Exception as exc:
                self.message_user(request, 'Не удалось разрешить расхождение %d: %s: %s' % (
                    inconsistency.pk, exc.__class__.__name__, exc.message)
                )
                errors += 1
            else:
                resolved += 1
        self.message_user(request, 'Успешно разрешено %d ролей, произошло %d ошибок' % (resolved, errors))
    resolve_inconsistencies.short_description = _('Разрешить')

    actions = ['resolve_inconsistencies']
    editable = False
    list_display = (
        'type',
        'state',
        'system',
        'user',
        'group',
        'added',
    )
    raw_id_fields = ('our_role', 'user', 'group', 'node')
    list_filter = ('state', 'type', 'system')
    search_fields = (
        'system__slug',
        'user__username',
        'group__name',
        'remote_username',
        'remote_group',
    )


site.register(Inconsistency, InconsistencyModelAdmin)
