from django.shortcuts import render, redirect
from django.db.models import Avg
from .forms import MediaUploadForm
from .models import MediaUpload, Rating

def index(request):
    if request.method == 'POST':
        form = MediaUploadForm(request.POST, request.FILES)
        if form.is_valid():
            media_upload = form.save()
            return redirect('media_detail', pk=media_upload.pk)
    else:
        form = MediaUploadForm()
    return render(request, 'core/index.html', {'form': form})

def media_detail(request, pk):
    media = MediaUpload.objects.get(pk=pk)
    ratings = media.ratings.all()
    average_rating = ratings.aggregate(Avg('score'))['score__avg']
    return render(request, 'core/media_detail.html', {'media': media, 'ratings': ratings, 'average_rating': average_rating})

def rate_media(request, pk):
    if request.method == 'POST':
        media_upload = MediaUpload.objects.get(pk=pk)
        score = request.POST.get('score')
        comment = request.POST.get('comment', '')
        if request.user.is_authenticated:
            rater = request.user
        else:
            rater = None

        if score:
            Rating.objects.create(media_upload=media_upload, score=score, comment=comment, rater=rater)
    return redirect('media_detail', pk=pk)