from django.shortcuts import render, get_object_or_404, redirect
from .models import Scene, Choice, PlayerProfile
from django.contrib.auth.decorators import login_required

def home(request):
    return render(request, "core/index.html")

@login_required
def scene_view(request, scene_id=None):
    player = request.user.playerprofile
    if scene_id:
        scene = get_object_or_404(Scene, id=scene_id)
        player.current_scene = scene
        player.save()
    else:
        scene = player.current_scene
        if not scene:
            first_scene = Scene.objects.first()
            if first_scene:
                player.current_scene = first_scene
                player.save()
                scene = first_scene
            else:
                return render(request, "core/empty.html")

    return render(request, "core/scene_detail.html", {"scene": scene, "player": player})

@login_required
def choose_action(request, choice_id):
    choice = get_object_or_404(Choice, id=choice_id)
    player = request.user.playerprofile
    if choice.next_scene:
        player.current_scene = choice.next_scene
        player.save()
        return redirect('core:scene_detail', scene_id=choice.next_scene.id)
    return redirect('core:current_scene')