from django.contrib import admin
from django.http import HttpResponseRedirect

from carnet_rouge.models import cr_Category, cr_Message
from django.contrib.auth.models import User
from django.contrib.admin import SimpleListFilter
from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _

from django_summernote.admin import SummernoteModelAdmin

class DefaultListFilter(SimpleListFilter):
    all_value = '_all'

    def default_value(self):
        raise NotImplementedError()

    def queryset(self, request, queryset):
        if self.parameter_name in request.GET and request.GET[self.parameter_name] == self.all_value:
            return queryset

        if self.parameter_name in request.GET:
            return queryset.filter(**{self.parameter_name:request.GET[self.parameter_name]})

        return queryset.filter(**{self.parameter_name:self.default_value()})

    def choices(self, cl):
        yield {
            'selected': self.value() == self.all_value,
            'query_string': cl.get_query_string({self.parameter_name: self.all_value}, []),
            'display': _('All'),
        }
        for lookup, title in self.lookup_choices:
            yield {
                'selected': self.value() == force_str(lookup) or (self.value() == None and force_str(self.default_value()) == force_str(lookup)),
                'query_string': cl.get_query_string({
                    self.parameter_name: lookup,
                }, []),
                'display': title,
            }

class StatusFilter(DefaultListFilter):
    title = _('Actif ')
    parameter_name = 'bEnabled__exact'

    def lookups(self, request, model_admin):
        return ((0,'Désactivé'), (1,'Activé'))

    def default_value(self):
        return 1

@admin.register(cr_Message)
class cr_Message_Admin(SummernoteModelAdmin):
    summernote_fields = ('sText',)
    class Meta:
        verbose_name = 'Message carnet rouge'
        verbose_name_plural = 'Messages carnet rouge'
    def save_model(self, request,obj , form, change):
        obj.Author = request.user
        obj.sAuthor = request.user.first_name + " " + request.user.last_name

        #Get all user of selected group
        obj.sDestUsers = "" # reset
        users_all = User.objects.filter(groups__name=obj.DestGroup.name)
        _con = ""
        for usr in users_all:
            obj.sDestUsers += f"{_con}[{usr.id}]"
            _con = ";"

        obj.sNotReadUsers = obj.sDestUsers
        obj.save()

    def has_change_permission(self, request, obj=None):
        if obj is not None and obj.Author != request.user :
            return False
        return True

    def has_delete_permission(self, request, obj=None):
        if obj is not None and obj.Author != request.user and not request.user.is_superuser:
            return False
        return True

    def response_change(self, request, obj):
        if "_temp_save" in request.POST:
            obj.bEnabled = False
            obj.save()
            self.message_user(request, _('Ce message a été enregistré en mode brouillon'))
            return HttpResponseRedirect(".")
        if "_publish_save" in request.POST:
            obj.bEnabled = True
            obj.save()
            self.message_user(request, _('Ce message a été publié'))
            return HttpResponseRedirect(".")
        return super().response_change(request, obj)




    always_show_username = True
    list_display = ('MessageId','sTitle', 'DestGroup', 'get_dtCreated',  'sAuthor','bEnabled', 'calc_read_quotas')
    list_filter = ["sAuthor", StatusFilter]
    fieldsets = (
        ('Message', {'fields': ("Caterogy", "DestGroup", 'sTitle', "sText") }),
        ('Validité', {'fields': ("dtValidityFrom", "dtValidityTo", "bEnabled")})
    )

    search_fields = ['sTitle', 'sText']


    """
    list_filter = [('dtDate', DateRangeFilter), ('user', admin.RelatedOnlyFieldListFilter),'sBases','type', 'bNoticed']

    search_fields = ['userName']
    readonly_fields = ["userName"]

    
    """


# Register your models here.
admin.site.register(cr_Category)
