from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404, redirect, render
from django.db.models import F, Count

from tickets.forms import TicketForm
from tickets.models import Ticket, TicketList


@login_required
def ticket_list_detail(request, pk=None, my_tickets=False, assignments=False):
    form = None
    ticket_list = None
    
    if my_tickets:
        tickets = Ticket.objects.filter(assigned_to=request.user) 
    elif assignments:
        tickets = Ticket.objects.filter(created_by=request.user)
    else:
        ticket_list = get_object_or_404(TicketList.objects.select_related('group'), id=pk)
        if ticket_list.group not in request.user.groups.all():
            raise PermissionDenied

        tickets = Ticket.objects.filter(ticket_list=ticket_list)

        form = TicketForm(
            request.user,
            initial={
                "ticket_list": ticket_list
            }
        )
    
    tickets = tickets.annotate(created_by_username=F("created_by__username"))
    tickets = tickets.annotate(assigned_to_username=F("assigned_to__username"))
    
    context = {
        "ticket_list": ticket_list,
        "tickets": tickets,
        "form": form,
        "my_tickets": my_tickets,
        "assignments": assignments
    }

    return render(request, "tickets/ticket_list_detail.html", context)
