from datetime import timedelta

from django import forms
from django.contrib.auth.models import Group
from django.utils import timezone

from tickets.models import Ticket, TicketList


class TicketForm(forms.ModelForm):
    ticket_type = forms.ChoiceField(
        choices=Ticket.TICKET_TYPES_CHOICES,
        widget=forms.Select(attrs={
                'class': 'form-control'
        }),
    )

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)

        group_ids = Group.objects.values_list("pk", flat=True)
        if not user.is_superuser:
            group_ids = group_ids.filter(user=user) 
        ticket_lists = TicketList.objects.select_related("group")
        ticket_lists = ticket_lists.filter(group__in=group_ids)

        self.fields["ticket_list"].empty_label = None
        self.fields["ticket_list"].queryset = ticket_lists
        self.fields["ticket_list"].label_from_instance = lambda obj: f"{obj.group} > {obj}"
        self.fields["assigned_to"].empty_label = "Select a user"
        self.initial["due_date"] = (timezone.now() + timedelta(days=7)).date().strftime('%Y-%m-%d')

    class Meta:
        model = Ticket
        exclude = ["status"]

        widgets = {
            'title': forms.TextInput(attrs={
                'class': 'form-control',
                'autofocus': True,
            }),
            'ticket_list': forms.Select(attrs={
                'class': 'form-control'
            }),
            'ticket_type': forms.Select(attrs={
                'class': 'form-control',
            }),
            'due_date': forms.DateInput(attrs={
                'class': 'form-control',
                'type': 'date'
            }),
            'assigned_to': forms.Select(attrs={
                'class': 'form-control'
            }),
            'note': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 4
            }),
            'priority': forms.NumberInput(attrs={
                'class': 'form-control',
            }),
        }
