from django.shortcuts import render, redirect
import os.path
import os
from .forms import ImageForm, VideoForm
from django.core.files.storage import FileSystemStorage
from .models import Image
from django.conf import settings

def uploadContent(request):
    if request.method == "GET":
        return render(request, "uploadChoice.html")
    elif request.method == "POST":
        choice = request.POST["choices"]
        if choice == "image":
            return redirect("/upload_image/")
        elif choice == "video":
            return redirect("/upload_video/")
        else:
            return
    else:
        return

# Please fix the fact that this shit gets uploaded literally everywhere

def imageUpload(request):
    """Process images uploaded by users"""

    print(request.user.id)
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            # Get the current instance object to display in the template
            userIdModel = Image.objects.filter(user=request.user.id)
            img_obj = form.instance
            img_obj.user = request.user
            form.save()
            return render(request, 'uploadImage.html', {'form': form, 'img_obj': img_obj})

    else:
        form = ImageForm()
    return render(request, 'uploadImage.html', {'form': form})

def videoUpload(request):
    """Process videos uploaded by users"""
    if request.method == 'POST':
        form = VideoForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            img_obj = form.instance
            return render(request, 'uploadVideo.html', {'form': form, 'img_obj': img_obj})

    else:
        form = VideoForm()
    return render(request, 'uploadVideo.html', {'form': form})

def viewMedia(request):
    path = settings.MEDIA_ROOT
    img_list = os.listdir(path + f"images/{request.user.id}/")
    context = {
    "images": img_list,
    "id":request.user.id,
    }
    return render (request, 'showAllImage.html', context)
