from django.contrib import admin
from rangefilter.filters import DateRangeFilter
from django.contrib.admin import DateFieldListFilter
from django.contrib.auth.models import User
from django.db.models import Q
from django.shortcuts import render
from django.contrib.auth.models import Permission
from django.utils.translation import gettext_lazy as _

from collabs.models import *

from django import forms
import datetime

from django.db import connection
print(connection.queries)

class myDateFilter(DateFieldListFilter):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        now = timezone.now()
        today = now.date()
        yesterday = today - datetime.timedelta(days=1)
        if today.month == 1:
            last_month = today.replace(year=today.year - 1, month=12, day=1)
        else:
            last_month = today.replace(month=today.month - 1, day=1)

        last_month_end = today.replace(day=1) -datetime.timedelta(days=1)




        self.links = list(self.links)
        self.links.insert(1, ('Mois dernier', {
            self.lookup_kwarg_since: str(last_month),
            self.lookup_kwarg_until: str(last_month_end),
        }))

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



class Collabs_hour_Form_admin(forms.ModelForm):

        model = Collabs_hour
        fields = ["user", "sRemarques", "bNoticed"]
        readonly_fields = ["user", "nHour", "nMinutes"]



class Collabs_hour_Admin(admin.ModelAdmin):
    always_show_username = True
    save_as = True



    class Meta:
        verbose_name = 'Heure supplémentaire'
        verbose_name_plural = 'Heures supplémentaires'
    list_display = ('dtDate', 'nHour', 'nMinutes', 'sTargetUser', 'sBases', 'type', 'get_total_hour_by_user', 'has_remarques', 'bNoticed')

    #list_filter = [('dtDate', DateRangeFilter), 'sTargetUser','sBases','type', 'bNoticed']
    list_filter = (('dtDate', myDateFilter),'sTargetUser', 'sBases', 'type', 'bNoticed')


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

    fields = ["sBases", "dtDate",'type', "user","nHour", "nMinutes", "sRemarques"]


    def get_rangefilter_dtDate_default(self, request):
        pass
        #return (datetime.today().replace(day=1), datetime.today())

    def get_queryset(self, request):
        queryset = super(Collabs_hour_Admin, self).get_queryset(request)


        if not is_member(request.user, "Administration"):
            #queryset = queryset.filter(Q(userName=request.user.username) | Q(user=request.user)) Désactivé pour le moment
            pass

        if not "dtDate__range__gte" in request.GET.keys() and "/change/" not in request.path:
            pass
            #start, end = self.get_rangefilter_dtDate_default(request)
            #queryset = queryset.filter(dtDate__range=[start,end])
            #queryset = queryset.filter(dtDate=start)

        return queryset




    def get_form(self, request, obj=None, **kwargs):
        #if request.user.has_perm("collabs.can_notice"):
        if request.user.is_superuser:
            #kwargs['form'] = Collabs_hour_Form_admin  # ModelForm
            print("PASS SUPERUSER")
        if obj != None:
           if (obj.userName == request.user.username or obj.user == request.user) and not obj.bNoticed:
               print("CAN EDIT 1")
               permission = Permission.objects.get(codename='change_collabs_hour')
               request.user.user_permissions.add(permission)
               request.user = User.objects.get(pk=request.user.id)
               print("CAN EDIT 2")
           else:
               print("RESET CAN EDIT 1")
               permission = Permission.objects.get(codename='change_collabs_hour')
               request.user.user_permissions.remove(permission)
               request.user.user_permissions.clear()
               request.user = User.objects.get(pk=request.user.id)
               print("RESET CAN EDIT 2")
        else:
            print("ERROR, NO object")

        return super().get_form(request, obj, **kwargs)

    def get_list_display(self, request):
        default_list_display = super(Collabs_hour_Admin, self).get_list_display(request)
        if request.user.has_perm('collabs.can_notice'):
            #default_list_display = ('dtDate', 'nHour', 'nMinutes', 'user', 'sBases', 'type', 'get_total_hour_by_user', 'has_remarques', 'bNoticed')
            pass
        else:
            default_list_display = ('dtDate', 'nHour', 'nMinutes', 'user', 'sBases', 'type', 'has_remarques')
        return default_list_display

    def get_list_editable(self, request):
        """
        get_list_editable method implementation,
        django ModelAdmin doesn't provide it.
        """
        dynamically_editable_fields = None
        if request.user.has_perm('collabs.can_notice'):
            dynamically_editable_fields = ('bNoticed',)
        return dynamically_editable_fields

    def get_changelist_instance(self, request):

        self.list_editable = self.get_list_editable(request)
        return super(Collabs_hour_Admin, self).get_changelist_instance(request)


    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        field = super(Collabs_hour_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(Collabs_hour_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)



    def save_model(self, request, obj, form, change):
        if obj.userName == "":
            obj.userName = request.user.username
        super().save_model(request, obj, form, change)


admin.site.register(Collabs_hour, Collabs_hour_Admin)
admin.site.register(Collabs_hour_types)
#admin.site.register(Collabs_hour)
