from django.contrib import admin
from django_summernote.admin import SummernoteModelAdmin
from studenteval.models import cl_Student_eval
from django.db.models import Q
from django.urls import reverse
from django.utils.html import format_html
from . import views
from django.contrib.auth.models import User
from rangefilter.filters import *
from django.core.exceptions import PermissionDenied

from rangefilter.filters import (
    DateRangeFilterBuilder,
    DateTimeRangeFilterBuilder,
    NumericRangeFilterBuilder,
    DateRangeQuickSelectListFilterBuilder,
)

def is_member(user, group):
    return user.groups.filter(name=group).exists()

class _cl_Student_eval_admin(SummernoteModelAdmin):
    summernote_fields = ('sDesc_neg','sDesc_pos','sDesc_global')
    request = None
    always_show_username = True
    list_per_page = 15    

    list_display = ('ID','action_buttons','sStudent', "get_ref_of_eval", "nEval_Type", "nEval_Mode", "sAuthor", 'get_mirrored')
    



    def action_buttons(self, obj):
        action1_url = f"/student_eval/show_pdf/{obj.uuid}/?dtDate__range__gte={self.request.GET.get('dtDate__range__gte')}&dtDate__range__lte={self.request.GET.get('dtDate__range__lte')}"
        return format_html('<a href="{}">Voir PDF</a>', action1_url)

    action_buttons.short_description = 'Voir la fiche PDF'

    def get_queryset(self, request):
        self.request = request
        user_obj = request.user
        if is_member(user_obj, "FI-Encadrants"):
             queryset = super().get_queryset(request)            
        elif is_member(user_obj, "FI-Étudiants"):
            queryset = super().get_queryset(request).filter(Q(Author=user_obj.id) | Q(Student=user_obj.id))
        elif is_member(user_obj, "Intervenants"):
           queryset = super().get_queryset(request).filter(Author=user_obj.id)
        else:
            raise PermissionDenied
        
        return queryset






    search_fields = ['sStudent', 'sRef']
    list_filter = ['sStudent',"sAuthor", "nEval_Type", "nEval_Mode",]
   #list_filter = ('sStudent', "sAuthor", "nEval_Type", "nEval_Mode", ("dtDate", DateRangeFilterBuilder()),)



    def get_form(self, request, obj=None, **kwargs):
        user_obj = request.user
        if obj is not None:
            author_id = obj.Author.id if obj.Author is not None else 0
            student_id = obj.Student.id if obj.Student is not None else 0

            if not user_obj.id == author_id and not user_obj.id == student_id and not is_member(user_obj, "FI-Encadrants"):
                raise PermissionDenied
        return super().get_form(request, obj, **kwargs)



    #fields = ["Vehicle", "nType",'sTitle', "sDesc","dtStart", "dtEnd", "Author"]

    fieldsets = (
        ('Informations générales', {
            'fields': ('Student','nEval_Type','dtDate','sRef')
        }),
        ("Information propre à l'intervention ou exercice", {
            'fields': ('sInter_Desc', 'nInter_Nature', 'nInter_Priority',  'nInter_Complexity', 'nStudent_Role')
        }),
        ("Appréciation de l'étudiant/stagiaire", {
            'fields': ("nEval_Mode", "sDesc_neg", 'sDesc_pos', "sDesc_global")
        }),
        ("Co-écriture du suivi", {
            'fields': ("Author_2e",)
        }),
    )


    def save_model(self, request, obj, form, change):
        if obj.Author is None:
            obj.Author = request.user
            obj.sAuthor = request.user.first_name + " " + request.user.last_name
        print("pass-Save")
        print(obj.Student)

        obj.sStudent = obj.Student.first_name + " " + obj.Student.last_name
        print(f"sStudent = {obj.sStudent}")

        print(obj.Author_2e)
        if obj.Author_2e is not None:
            print(f"Maj author 2e")
            obj.sAuthor_2e = obj.Author_2e.first_name + " " + obj.Author_2e.last_name

        obj.save()

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        field = super(_cl_Student_eval_admin, self).formfield_for_foreignkey(                                                db_field, request, **kwargs)
        if db_field.remote_field.model == User:
            field.label_from_instance = self.get_user_label
        return field

    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        field = super(_cl_Student_eval_admin, self).formfield_for_manytomany(                                                db_field, request, **kwargs)
        if db_field.remote_field.model == User:
            field.label_from_instance = self.get_user_label
        return field

    def get_user_label(self, user):
        name = user.get_full_name()
        username = user.username
        if not self.always_show_username:
            return name or username
        return (name and name != username and '%s (%s)' % (name, username)                or username)




# Register your models here.
admin.site.register(cl_Student_eval, _cl_Student_eval_admin)
