from django.shortcuts import render, get_object_or_404
from .models import *
from .decorators import *
from osinacore.decorators import *
from django.http import Http404

# Create your views here.
def ticket_room(request, ticket_number):
    ticket = get_object_or_404(Ticket, ticket_number=ticket_number)
    if request.user.is_superuser:
        base_template = "main.html"
    elif hasattr(request.user, 'customerprofile') and request.user.customerprofile == ticket.customer:
        base_template = "customer_main.html"
    elif hasattr(request.user, 'staffprofile') and request.user.staffprofile in ticket.get_all_ticket_staff():
            base_template = "main.html"
    else:
        raise Http404("You are not authorized to view this ticket.")


    ticket_updates = TicketUpdate.objects.filter(ticket=ticket).order_by('id')
    for update in TicketUpdate.objects.filter(ticket=ticket).exclude(added_by=request.user).order_by('id'):
        if not TicketRead.objects.filter(ticket_update=update, user=request.user).exists():
            TicketRead.objects.create(ticket_update=update, user=request.user, read=True)

    last_ticket_status = TicketStatus.objects.filter(ticket=ticket).last()
    last_ticket_department = TicketDepartment.objects.filter(ticket=ticket).last()

    connections = TicketConnection.objects.filter(terminated_at__isnull=True).order_by('-id')

    context = {     
        'base_template': base_template,
        'ticket' : ticket,
        'ticket_updates': ticket_updates,
        'last_ticket_status': last_ticket_status,
        'last_ticket_department': last_ticket_department,
        'connections': connections,

    }

    return render(request, 'details_templates/ticket-room.html', context)





def get_last_seen_order_key(member):
    last_seen_text = member.get_last_seen()
    
    if last_seen_text == "Online":
        return (0, datetime.max)
    elif "last seen today" in last_seen_text:
        time_part = last_seen_text.split(" at ")[-1]
        last_seen_time = datetime.strptime(time_part, '%I:%M %p')
        return (1, last_seen_time)
    elif "last seen yesterday" in last_seen_text:
        time_part = last_seen_text.split(" at ")[-1]
        last_seen_time = datetime.now() - timedelta(days=1)
        last_seen_time = last_seen_time.replace(hour=datetime.strptime(time_part, '%I:%M %p').hour,
                                                minute=datetime.strptime(time_part, '%I:%M %p').minute)
        return (2, last_seen_time)
    elif "last seen on" in last_seen_text:
        date_time_part = last_seen_text.split(" on ")[-1]
        last_seen_time = datetime.strptime(date_time_part, '%b %d at %I:%M %p')
        return (3, last_seen_time)
    else:
        return (4, datetime.min)



@staff_login_required
def ticket_settings(request, ticket_number):
    ticket = get_object_or_404(Ticket, ticket_number=ticket_number)
    ticket_departments = TicketDepartment.objects.filter(ticket=ticket).order_by('-id')
    ticket_members = TicketStaff.objects.filter(ticket=ticket)
    ticket_members = sorted(ticket_members, key=get_last_seen_order_key)
    customer_last_seen = ticket.get_customer_last_seen()

    context = {     
        'ticket': ticket,
        'ticket_departments': ticket_departments,
        'ticket_members': ticket_members,
        'customer_last_seen': customer_last_seen,

    }

    return render(request, 'details_templates/ticket-settings.html', context)



