from .models import *
from django.contrib.auth.models import AnonymousUser
from datetime import datetime, timedelta
from django.shortcuts import get_object_or_404


def calculate_time_ago(status):
    # Convert status.date to a datetime.date object
    status_date = datetime.strptime(status.date, '%Y-%m-%d').date()
    timestamp = datetime.combine(status_date, datetime.strptime(status.time, '%I:%M %p').time())
    time_difference = datetime.now() - timestamp

    if time_difference.total_seconds() < 3600:
        # If less than an hour, display in minutes
        return f"{int(time_difference.total_seconds() / 60)}min ago"
    else:
        # Display in hours and remaining minutes
        hours = int(time_difference.total_seconds() // 3600)
        minutes = int((time_difference.total_seconds() % 3600) // 60)
        return f"{hours}hr {minutes}min ago"


def utilities(request):
    last_connections = Connection.objects.order_by('user', '-date').distinct('user')

    online_staff_profiles = []

    for connection in last_connections:
        if connection.status == 'Online':
            # Add user staff profile to online_staff_profiles
            online_staff_profiles.append(connection.user.staffprofile)
    notes = None
    recent_note = None
    if request.user.is_authenticated:
        notes = Note.objects.filter(user=request.user).order_by('-date')[:6]
        recent_note = Note.objects.filter(user=request.user).last()

    if request.user.is_authenticated and request.user.is_superuser:
        open_task_count = Task.objects.filter(status='Open').count()
        working_on_task_count = Task.objects.filter(status='Working On').count()
    
    elif request.user.is_authenticated:
        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()
        

    else:
        # Handle the case when the user is not logged in
        open_task_count = 0
        working_on_task_count = 0
       
    
    total_tasks = open_task_count + working_on_task_count


    # Get the current time
    current_time = timezone.now()

    # Calculate the datetime of 24 hours ago
    twenty_four_hours_ago = current_time - timezone.timedelta(hours=24)

    # Fetch the latest statuses from the last 24 hours
    latest_statuses = Status.objects.filter(date__gte=twenty_four_hours_ago).order_by('-id')

    # Calculate time ago for each status and store it in a dictionary
    latest_statuses_time_ago = [{'status': status, 'time_ago': calculate_time_ago(status)} for status in latest_statuses]
 
    
    return {'total_tasks': total_tasks, 
            'latest_statuses' : latest_statuses, 
            'latest_statuses_time_ago': latest_statuses_time_ago,  
            'notes' : notes, 
            'recent_note' : recent_note,
            'online_staff_profiles' : online_staff_profiles,
}


def last_status(request):
    minutes_ago = 0 
    hours_ago = 0 
    hours_minutes_ago = ""
    current_date = datetime.now().strftime('%Y-%m-%d')
    if request.user.is_authenticated:
        last_status = Status.objects.filter(staff=request.user.staffprofile).last()
        if last_status:
            # Convert the 'time' field to a datetime object
            status_time = datetime.strptime(last_status.time, '%I:%M %p')

            # Get the current time
            current_time = datetime.now().time()

            # Calculate the time difference
            time_difference = abs(datetime.combine(datetime.today(), current_time) - datetime.combine(datetime.today(), status_time.time()))
            # Get the time difference in minutes
            minutes_ago = time_difference.total_seconds() / 60
            minutes_ago = int(minutes_ago)

    else:
        # Handle the case when the user is not logged in
        last_status = None
    
    if minutes_ago > 60:
        hours_ago = minutes_ago // 60  # Calculate the number of hours
        remaining_minutes = minutes_ago % 60  # Calculate the remaining minutes
        hours_minutes_ago = f"{hours_ago}hr {remaining_minutes}min ago"
    else:
        hours_minutes_ago = f"{minutes_ago}min ago"

    

    return {'last_status' : last_status, 'current_date' : current_date, 'minutes_ago' : minutes_ago, 'hours_minutes_ago': hours_minutes_ago}




