from billing.models import *
from osinacore.models import *
from customercore.models import *
from support.models import *
from django.db.models import Count, Q

def utilities(request):
    active_subscriptions = None
    customer_open_tickets = None
    customer_open_tickets_count = None
    customer_open_projects = None
    customer_open_projects_count =  None
    customer_open_invoices_count = None
    if request.user.is_authenticated and CustomerProfile.objects.filter(user=request.user):
        customer = request.user.customerprofile
        active_subscriptions = OrderItem.objects.filter(active=True, order__customer=customer)

        customer_open_projects = Project.objects.filter(active=True, customer=customer)
        customer_open_projects_count = customer_open_projects.count()

        orders_with_invoice = Order.objects.filter(customer=customer, invoice__isnull=False)
        orders_without_completed_status = orders_with_invoice.exclude(orderstatus__status='Completed')
        customer_open_invoices_count = orders_without_completed_status.count()

        customer_open_tickets = Ticket.objects.filter(customer=request.user.customerprofile).exclude(ticketstatus__status='Closed').order_by('-id')
        customer_open_tickets_count = customer_open_tickets.count()

        for ticket in customer_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

    return {'active_subscriptions': active_subscriptions, 'customer_open_tickets': customer_open_tickets, 'customer_open_tickets_count':customer_open_tickets_count, 'customer_open_projects_count': customer_open_projects_count, 'customer_open_invoices_count': customer_open_invoices_count}
