from .models import *
from django.contrib.auth.models import AnonymousUser
from datetime import datetime, timedelta
from django.shortcuts import get_object_or_404
from django.db.models import Max, F
from support.models import *
from osichat.models import *


def utilities(request):


    notes = None
    recent_note = None
    user_offline=None
    open_task_count = 0
    working_on_task_count = 0
    total_tasks = 0
    open_tickets = None
    closed_tickets = None
    latest_statuses = None
    last_status = None
    today = timezone.now()

    if request.user.is_authenticated and StaffProfile.objects.filter(user=request.user):
        notes = Note.objects.filter(user=request.user).order_by('-date')[:6]
        recent_note = Note.objects.filter(user=request.user).last()

        if request.user.is_superuser:
            open_task_count = Task.objects.filter(status='Open').count()
            working_on_task_count = Task.objects.filter(status='Working On').count()
            total_tasks = open_task_count + working_on_task_count


            all_tickets = Ticket.objects.all()
            all_tickets_with_update_date = all_tickets.annotate(latest_update_date=Max('ticketupdate__date_added'))
            all_tickets_ordered = all_tickets_with_update_date.order_by('-latest_update_date')
            open_tickets = []
            closed_tickets = []
            for ticket in all_tickets_ordered:
                last_status = ticket.ticketstatus_set.last()
                if last_status:
                    last_status = last_status.status
                    if last_status == 'Closed':
                        closed_tickets.append(ticket)
                    else:
                        open_tickets.append(ticket)
                else:
                    # If no status is found, assume it's open
                    open_tickets.append(ticket)


        else: 
            open_task_count = Task.objects.filter(assigned_to=request.user.staffprofile, status='Open').count()
            working_on_task_count = Task.objects.filter(assigned_to=request.user.staffprofile, status='Working On').count()
            total_tasks = open_task_count + working_on_task_count
            all_tickets = Ticket.objects.all()
            filtered_tickets = []
            for ticket in all_tickets:
                staff_profiles = ticket.get_all_ticket_staff()
                if any(staff.user == request.user for staff in staff_profiles):
                    filtered_tickets.append(ticket)

            all_tickets = Ticket.objects.filter(id__in=[ticket.id for ticket in filtered_tickets]).annotate(
            latest_update_date=Max('ticketupdate__date_added'))
            all_tickets_with_update_date = all_tickets.annotate(latest_update_date=Max('ticketupdate__date_added'))
            all_tickets_ordered = all_tickets_with_update_date.order_by('-latest_update_date')
                
            open_tickets = []
            closed_tickets = []
            for ticket in all_tickets_ordered:
                last_status = ticket.ticketstatus_set.last()
                if last_status:
                    last_status = last_status.status
                    if last_status == 'Closed':
                        closed_tickets.append(ticket)
                    else:
                        open_tickets.append(ticket)
                else:
                    # If no status is found, assume it's open
                    open_tickets.append(ticket)
    

        for ticket in open_tickets:
            unread_updates_count = 0
            for ticket_update in ticket.ticketupdate_set.exclude(added_by=request.user): 
                if not TicketRead.objects.filter(ticket_update=ticket_update, user=request.user, read=True).exists():
                    unread_updates_count += 1

            ticket.unread_updates_count = unread_updates_count

        latest_statuses = Status.objects.filter(date_time__date=today).order_by('-id')
        last_status = Status.objects.filter(staff=request.user.staffprofile).last()



       

    recent_logged_in_staffs = User.objects.filter(
        staffprofile__isnull=False, 
        last_login__isnull=False  
    ).order_by('-last_login')[:8] 

    recent_logged_in_customers = User.objects.filter(
        customerprofile__isnull=False, 
        last_login__isnull=False 
    ).order_by('-last_login')[:8]  

    latest_chat_rooms = ChatRoom.objects.annotate(last_update=Max('chatmessage__date_sent')).order_by('-last_update', '-date_created')
    
    return {
            'total_tasks': total_tasks, 
            'latest_statuses' : latest_statuses, 
            'last_status': last_status,
            'notes' : notes, 
            'recent_note' : recent_note,
            'user_offline' : user_offline,
            'recent_logged_in_staffs' : recent_logged_in_staffs,
            'recent_logged_in_customers' : recent_logged_in_customers,
            'open_tickets': open_tickets,
            'closed_tickets': closed_tickets,
            'today': today,
            'latest_chat_rooms': latest_chat_rooms,

}