<reponame>fross123/Theater-Admin-Portal
import datetime
from django.http.response import JsonResponse
from django.utils.timezone import now

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.core import serializers


from django.core.mail import send_mail

from shows.models import Call, Performance, Rehearsal, Show
from audition.models import AuditionSlot, Application

from users.forms import UserCreateForm

# Create your views here.
@login_required()
def profile(request):
    """
    Audition Slots, Performances and Rehearsals that the user are a part of are displayed.
    - For Performances and Rehearsals, the user must be in the call list.

    template: users/profile.html
    """
    upcoming_slots = []
    past_slots = []
    # Loop through the applications submitted by the user.
    for application in Application.objects.filter(user=request.user):
        # Loop through slots for that application. (Should only be one)
        for slot in AuditionSlot.objects.filter(application=application):
            # if user has permission to view the audition slot.
            if request.user.has_perm('audition.view_auditionslot', slot):
                # if the slot is in the future
                if slot.end > now():
                    # if slot is 48 hours in future, confirm button should be displayed.
                    future_date = now() + datetime.timedelta(hours=48)
                    if slot.start < future_date and slot.confirmed is None:
                        upcoming_slots.append({"slot": slot, 'confirm_button': True})
                    else:
                        upcoming_slots.append({"slot": slot, 'confirm_button': False})
                # slot is in the past
                elif slot.end < now():
                    past_slots.append(slot)

    shows = []
    for show in Show.objects.order_by('start_date').filter(end_date__gt=now()):
        if request.user.has_perm('shows.view_applications', show) or request.user.has_perm('shows.view_applications'):
            show = {'show': show, 'view_applications': True, 'badge': 'Casting'}
            shows.append(show)

        elif request.user in show.production_staff.all():
            show = {'show': show, 'view_applications': False, 'badge': 'Staff'}
            shows.append(show)

        elif request.user in show.performers.all():
            show = {'show': show, 'view_applications': False, 'badge': 'Cast'}
            shows.append(show)

        elif request.user.has_perm('shows.view_show', show) or request.user.has_perm('shows.view_show'):
            show = {'show': show, 'view_applications': False}
            shows.append(show)

    calls = []
    for call in Call.objects.filter(users=request.user):
        if Rehearsal.objects.filter(calls=call):
            for reh in Rehearsal.objects.filter(calls=call):
                if reh.end > now():
                    calls.append({"call": call, "obj": reh, "type": "rehearsal"})

        if Performance.objects.filter(calls=call):
            for perf in Performance.objects.filter(calls=call):
                if perf.end > now():
                    calls.append({"call": call, "obj": perf, "type": "performance"})

    return render(request, "users/profile.html", {
        'upcoming_slots': sorted(upcoming_slots[:10], key=lambda slot: slot["slot"].start),
        'past_slots': sorted(past_slots[:10], key=lambda slot: slot.start, reverse=True),
        'shows': shows,
        'calls': sorted(calls[:10], key=lambda obj: obj["obj"].start)
    })

@login_required()
def profile_schedule(request):
    """
    Renders the profile schedule
    
    template: users/profile_schedule.html
    """
    if request.method == "GET":
        return render(request, "users/profile_schedule.html")


@login_required()
def profile_events(request):
    """
    Returns a JsonResponse of the relevent events for the currently logged in user.

    This view is called via a fetch request from users/profile_schedule.html
    """
    slots = []
    # Loop through the applications submitted by the user.
    for application in Application.objects.filter(user=request.user):
        # Loop through slots for that application. (Should only be one)
        for slot in AuditionSlot.objects.filter(application=application):
            # if user has permission to view the audition slot.
            if request.user.has_perm('audition.view_auditionslot', slot):
                slots.append(slot)
    data = serializers.serialize("json", slots, fields=('start', 'end', 'show'), use_natural_foreign_keys=True, use_natural_primary_keys=True)

    performances = []
    rehearsals = []
    for call in Call.objects.filter(users=request.user):
        if Performance.objects.filter(calls=call):
            for perf in Performance.objects.filter(calls=call):
                performances.append(perf)

        if Rehearsal.objects.filter(calls=call):
            for reh in Rehearsal.objects.filter(calls=call):
                rehearsals.append(reh)
    
    performances = serializers.serialize('json', performances, fields=('start', 'end', 'show'), use_natural_foreign_keys=True, use_natural_primary_keys=True)
    rehearsals = serializers.serialize('json', rehearsals, fields=('start', 'end', 'show'), use_natural_foreign_keys=True, use_natural_primary_keys=True)    

    return JsonResponse({
        'slots': data,
        'performances': performances,
        'rehearsals': rehearsals,
    })

import datetime
from django.http.response import JsonResponse
from django.utils.timezone import now

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.core import serializers


from django.core.mail import send_mail

from shows.models import Call, Performance, Rehearsal, Show
from audition.models import AuditionSlot, Application

from users.forms import UserCreateForm

# Create your views here.
@login_required()
def profile(request):
    """
    Audition Slots, Performances and Rehearsals that the user are a part of are displayed.
    - For Performances and Rehearsals, the user must be in the call list.

    template: users/profile.html
    """
    upcoming_slots = []
    past_slots = []
    # Loop through the applications submitted by the user.
    for application in Application.objects.filter(user=request.user):
        # Loop through slots for that application. (Should only be one)
        for slot in AuditionSlot.objects.filter(application=application):
            # if user has permission to view the audition slot.
            if request.user.has_perm('audition.view_auditionslot', slot):
                # if the slot is in the future
                if slot.end > now():
                    # if slot is 48 hours in future, confirm button should be displayed.
                    future_date = now() + datetime.timedelta(hours=48)
                    if slot.start < future_date and slot.confirmed is None:
                        upcoming_slots.append({"slot": slot, 'confirm_button': True})
                    else:
                        upcoming_slots.append({"slot": slot, 'confirm_button': False})
                # slot is in the past
                elif slot.end < now():
                    past_slots.append(slot)

    shows = []
    for show in Show.objects.order_by('start_date').filter(end_date__gt=now()):
        if request.user.has_perm('shows.view_applications', show) or request.user.has_perm('shows.view_applications'):
            show = {'show': show, 'view_applications': True, 'badge': 'Casting'}
            shows.append(show)

        elif request.user in show.production_staff.all():
            show = {'show': show, 'view_applications': False, 'badge': 'Staff'}
            shows.append(show)

        elif request.user in show.performers.all():
            show = {'show': show, 'view_applications': False, 'badge': 'Cast'}
            shows.append(show)

        elif request.user.has_perm('shows.view_show', show) or request.user.has_perm('shows.view_show'):
            show = {'show': show, 'view_applications': False}
            shows.append(show)

    calls = []
    for call in Call.objects.filter(users=request.user):
        if Rehearsal.objects.filter(calls=call):
            for reh in Rehearsal.objects.filter(calls=call):
                if reh.end > now():
                    calls.append({"call": call, "obj": reh, "type": "rehearsal"})

        if Performance.objects.filter(calls=call):
            for perf in Performance.objects.filter(calls=call):
                if perf.end > now():
                    calls.append({"call": call, "obj": perf, "type": "performance"})

    return render(request, "users/profile.html", {
        'upcoming_slots': sorted(upcoming_slots[:10], key=lambda slot: slot["slot"].start),
        'past_slots': sorted(past_slots[:10], key=lambda slot: slot.start, reverse=True),
        'shows': shows,
        'calls': sorted(calls[:10], key=lambda obj: obj["obj"].start)
    })

@login_required()
def profile_schedule(request):
    """
    Renders the profile schedule
    
    template: users/profile_schedule.html
    """
    if request.method == "GET":
        return render(request, "users/profile_schedule.html")


@login_required()
def profile_events(request):
    """
    Returns a JsonResponse of the relevent events for the currently logged in user.

    This view is called via a fetch request from users/profile_schedule.html
    """
    slots = []
    # Loop through the applications submitted by the user.
    for application in Application.objects.filter(user=request.user):
        # Loop through slots for that application. (Should only be one)
        for slot in AuditionSlot.objects.filter(application=application):
            # if user has permission to view the audition slot.
            if request.user.has_perm('audition.view_auditionslot', slot):
                slots.append(slot)
    data = serializers.serialize("json", slots, fields=('start', 'end', 'show'), use_natural_foreign_keys=True, use_natural_primary_keys=True)

    performances = []
    rehearsals = []
    for call in Call.objects.filter(users=request.user):
        if Performance.objects.filter(calls=call):
            for perf in Performance.objects.filter(calls=call):
                performances.append(perf)

        if Rehearsal.objects.filter(calls=call):
            for reh in Rehearsal.objects.filter(calls=call):
                rehearsals.append(reh)
    
    performances = serializers.serialize('json', performances, fields=('start', 'end', 'show'), use_natural_foreign_keys=True, use_natural_primary_keys=True)
    rehearsals = serializers.serialize('json', rehearsals, fields=('start', 'end', 'show'), use_natural_foreign_keys=True, use_natural_primary_keys=True)    

    return JsonResponse({
        'slots': data,
        'performances': performances,
        'rehearsals': rehearsals,
    })
# Create your views here. Audition Slots, Performances and Rehearsals that the user are a part of are displayed.     - For Performances and Rehearsals, the user must be in the call list.      template: users/profile.html # Loop through the applications submitted by the user. # Loop through slots for that application. (Should only be one) # if user has permission to view the audition slot. # if the slot is in the future # if slot is 48 hours in future, confirm button should be displayed. # slot is in the past Renders the profile schedule          template: users/profile_schedule.html Returns a JsonResponse of the relevent events for the currently logged in user.      This view is called via a fetch request from users/profile_schedule.html # Loop through the applications submitted by the user. # Loop through slots for that application. (Should only be one) # if user has permission to view the audition slot.