# Create your views here.
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required

from rest_framework.response import Response
from rest_framework.decorators import api_view

from .models import Artista, Album, Song
from .forms import ArtistaForm, AlbumForm, SongForm
from .serializers import ArtistaSerializer, AlbumSerializer, CancionSerializer

import logging
logger = logging.getLogger(__name__)


@login_required
def principal(request):
    artistas = Artista.objects.all()
    albumes = Album.objects.all()

    return render(request, 'lyrics/index.html', {'artistas': artistas, 'albumes': albumes})


#########################
# Vistas para los artistas
@login_required
def lista_artistas(request):
    artistas = Artista.objects.all()
    return render(request, 'lyrics/lista_artistas.html', {'artistas': artistas})


@login_required
def detalle_artista(request, artista_id):
    artista = get_object_or_404(Artista, pk=artista_id)

    albumes = Album.objects.filter(artist=artista_id)

    return render(request, 'lyrics/detalle_artista.html', {'artista': artista, 'albumes': albumes})


@login_required
def nuevo_artista(request):
    if request.method == 'POST':
        form = ArtistaForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('lyrics:lista_artistas')
    else:
        form = ArtistaForm()
    return render(request, 'lyrics/form_artista.html', {'form': form})


@login_required
def editar_artista(request, artista_id):
    artista = get_object_or_404(Artista, pk=artista_id)
    if request.method == 'POST':
        form = ArtistaForm(request.POST, request.FILES, instance=artista)
        if form.is_valid():
            form.save()
            return redirect('lyrics:lista_artistas')
    else:
        form = ArtistaForm(instance=artista)
    return render(request, 'lyrics/form_artista.html', {'form': form})


@login_required
def eliminar_artista(request, artista_id):
    artista = get_object_or_404(Artista, pk=artista_id)
    artista.delete()
    return redirect('lyrics:lista_artistas')


#########################
# Vistas para los albumes
@login_required
def lista_albumes(request):
    albumes = Album.objects.all()
    return render(request, 'lyrics/lista_albumes.html', {'albumes': albumes})


@login_required
def detalle_album(request, album_id):
    album = get_object_or_404(Album, pk=album_id)
    songs = Song.objects.filter(album_id=album_id).order_by("pista")

    return render(request, 'lyrics/detalle_album.html', {'album': album, 'songs': songs})


@login_required
def nuevo_album(request):

    artistas = Artista.objects.all()  # vamos a ver si hay vehículos dados de alta

    if artistas:
        if request.method == 'POST':
            form = AlbumForm(request.POST, request.FILES)
            if form.is_valid():
                form.save()

                return redirect('lyrics:lista_albumes')
        else:
            form = AlbumForm()
        return render(request, 'lyrics/form_album.html', {'form': form})
    else:
        return render(request, 'lyrics/index.html')


@login_required
def editar_album(request, album_id):
    album = get_object_or_404(Album, pk=album_id)

    if request.method == 'POST':
        form = AlbumForm(request.POST, request.FILES, instance=album)
        if form.is_valid():
            form.save()
            return redirect('lyrics:lista_albumes')
    else:
        form = AlbumForm(instance=album)
    return render(request, 'lyrics/form_album.html', {'form': form})


@login_required
def eliminar_album(request, album_id):
    album = Album.objects.get(pk=album_id)
    album.delete()
    return redirect('lyrics:lista_albumes')


#########################
# Vistas para los songs
@login_required
def lista_songs(request):
    songs = Song.objects.all()
    return render(request, 'lyrics/lista_songs.html', {'songs': songs})


@login_required
def detalle_song(request, song_id):
    song = get_object_or_404(Song, pk=song_id)

    albumes = Album.objects.filter(song=song_id)

    return render(request, 'lyrics/detalle_song.html', {'song': song, 'albumes': albumes})


@login_required
def nuevo_song(request):
    album_id = request.GET.get('album_id')  # Obtener el album_id de los parámetros de la URL

    if request.method == 'POST':
        form = SongForm(request.POST, request.FILES)
        if form.is_valid():
            album = form.cleaned_data['album']

            song_count = album.song.count()

            nueva_cancion = form.save(commit=False)

            nueva_cancion.pista = song_count + 1

            nueva_cancion.save()

            logger.info("Canción creada %s", nueva_cancion.title)

            return redirect('lyrics:lista_songs')
    else:
        if album_id:
            # Si tenemos un album_id, preseleccionamos ese álbum en el formulario
            album = get_object_or_404(Album, id=album_id)
            form = SongForm(initial={'album': album, 'artist': album.artist, 'year': album.year})
        else:
            form = SongForm()

    return render(request, 'lyrics/form_song.html', {'form': form})


@login_required
def editar_song(request, song_id):
    song = get_object_or_404(Song, pk=song_id)
    if request.method == 'POST':
        form = SongForm(request.POST, request.FILES, instance=song)
        if form.is_valid():
            form.save()
            return redirect('lyrics:lista_songs')
    else:
        form = SongForm(instance=song)
    return render(request, 'lyrics/form_song.html', {'form': form})


@login_required
def eliminar_song(request, song_id):
    song = get_object_or_404(Song, pk=song_id)
    song.delete()
    return redirect('lyrics:lista_songs')


@api_view(['GET'])
def api_lista_artistas(request):
    """Devuelve la lista de todos los artistas."""
    artistas = Artista.objects.all()
    serializer = ArtistaSerializer(artistas, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def api_detalle_artista(request, artista_id):
    """Devuelve los detalles de un artista específico."""
    try:
        artista = Artista.objects.get(id=artista_id)
        serializer = ArtistaSerializer(artista)
        return Response(serializer.data)
    except Artista.DoesNotExist:
        return Response({'error': 'Artista no encontrado'}, status=404)


@api_view(['GET'])
def api_lista_albumes(request):
    """Devuelve la lista de todos los albumes."""
    albumes = Album.objects.all()
    serializer = AlbumSerializer(albumes, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def api_detalle_album(request, album_id):
    """Devuelve los detalles de un album específico."""
    try:
        album = Album.objects.get(id=album_id)
        serializer = AlbumSerializer(album)
        return Response(serializer.data)
    except Album.DoesNotExist:
        return Response({'error': 'Album no encontrado'}, status=404)


@api_view(['GET'])
def api_lista_canciones(request):
    """Devuelve la lista de todos los canciones."""
    canciones = Song.objects.all()
    serializer = CancionSerializer(canciones, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def api_detalle_cancion(request, cancion_id):
    """Devuelve los detalles de un cancion específica."""
    try:
        cancion = Song.objects.get(id=cancion_id)
        serializer = CancionSerializer(cancion)
        return Response(serializer.data)
    except Song.DoesNotExist:
        return Response({'error': 'Canción no encontrada'}, status=404)
