# views.py
from email import message
import logging

from django.shortcuts import get_object_or_404, redirect, render
from django.http import HttpRequest
from django.urls import reverse
from django.contrib import messages

from events.utils.cookieutils import get_rsvp_from_cookie, set_rsvp_cookie

from ..models import (
    Event,
    Activity,
    RSVP,
)

# Logger
logger = logging.getLogger(__name__)

def invite_redirect(request:HttpRequest, slug:str):
    """
    Redirect from the unique invite page
    to the rsvp response page which is linked to the response
    """
    
    rsvp = get_object_or_404(RSVP, invite=slug)
    response = redirect(reverse('events:event', args=[rsvp.event.slug]))
    
    # Opened for the first time
    #TODO what is email not sent out?
    if(rsvp.status == RSVP.Status.UNOPENED):
        rsvp.status = RSVP.Status.NOT_STARTED
        rsvp.save()
        
        # Only set the cookie the first time, after this they need to use the invite link
        set_rsvp_cookie(response, rsvp.event, rsvp)
    else:
        messages.warning(request, "You can only use the invite once, please use the link in the email.")
    
    logger.info(f"Invite `{slug}` opened for Event `{rsvp.event.title}`")
    
    return response


def event(request:HttpRequest, slug):
    event = get_object_or_404(Event, slug=slug)
    
    activities = (
        Activity.objects
        .filter(event=event)
        .select_related("group")
        .order_by("start_time")
    )
    
    groups = {}
    ungrouped = []

    for activity in activities:
        
        if activity.group:
            groups.setdefault(activity.group, []).append(activity)
        else:
            ungrouped.append(activity)
    
    context = {
        "event": event,
        "groups": groups,
        "ungrouped_activities": ungrouped,
        
    }
    
    response = False
    
    rsvp = get_rsvp_from_cookie(request, slug)
    if type(rsvp) is RSVP:
        
        joining = True if rsvp.status == RSVP.Status.YES_JOINING else False
        not_coming = True if rsvp.status == RSVP.Status.NOT_COMING else False
        in_progress = True if rsvp.status == RSVP.Status.INCOMPLETE else False
        not_started = True if rsvp.status == RSVP.Status.NOT_STARTED or rsvp.status == RSVP.Status.UNOPENED else False
        
        response = {
            "rsvp": rsvp,
            "joining": joining,
            "not_coming": not_coming,
            "in_progress": in_progress,
            "not_started": not_started
        }
        
    context["response"] = response

    return render(request, "event/event.html", context)