# 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 Vehiculo, Repostaje
from .forms import VehiculoForm, RepostajeForm
from .serializers import VehiculoSerializer, RepostajeSerializer

import logging

logger_info = logging.getLogger('repostajes')
logger_debug = logging.getLogger('django')

@login_required
def principal(request):
    vehiculos = Vehiculo.objects.all()
    repostajes = Repostaje.objects.all()

    logger_debug.debug("Rendering principal view with %d vehiculos and %d repostajes", vehiculos.count(), repostajes.count())   
    logger_info.info("User %s accessed principal view", request.user.nombre if request.user.is_authenticated else "Anonymous") 

    return render(request, 'repostajes/index.html', {'vehiculos': vehiculos, 'repostajes': repostajes})


# Vistas para los vehiculos
@login_required
def lista_vehiculos(request):
    vehiculos = Vehiculo.objects.all()
    return render(request, 'repostajes/lista_vehiculos.html', {'vehiculos': vehiculos})


@login_required
def detalle_vehiculo(request, vehiculo_id):
    vehiculo = get_object_or_404(Vehiculo, pk=vehiculo_id)

    repostajes = Repostaje.objects.filter(vehiculo=vehiculo_id).order_by('-fecha')

    return render(request, 'repostajes/detalle_vehiculo.html', {'vehiculo': vehiculo, 'repostajes': repostajes})


@login_required
def nuevo_vehiculo(request):
    if request.method == 'POST':
        form = VehiculoForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('repostajes:lista_vehiculos')
    else:
        form = VehiculoForm()
    return render(request, 'repostajes/form_vehiculo.html', {'form': form})


@login_required
def editar_vehiculo(request, vehiculo_id):
    vehiculo = get_object_or_404(Vehiculo, pk=vehiculo_id)
    if request.method == 'POST':
        form = VehiculoForm(request.POST, request.FILES, instance=vehiculo)
        if form.is_valid():
            form.save()
            return redirect('repostajes:lista_vehiculos')
    else:
        form = VehiculoForm(instance=vehiculo)
    return render(request, 'repostajes/form_vehiculo.html', {'form': form})


@login_required
def eliminar_vehiculo(request, vehiculo_id):
    vehiculo = get_object_or_404(Vehiculo, pk=vehiculo_id)
    vehiculo.delete()
    return redirect('repostajes:lista_vehiculos')


# Vistas para los repostajes
@login_required
def lista_repostajes(request):
    repostajes = Repostaje.objects.all().order_by('-fecha')
    return render(request, 'repostajes/lista_repostajes.html', {'repostajes': repostajes})


@login_required
def detalle_repostaje(request, repostaje_id):
    repostaje = get_object_or_404(Repostaje, pk=repostaje_id)
    return render(request, 'repostajes/detalle_repostaje.html', {'repostaje': repostaje})


@login_required
def nuevo_repostaje(request):

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

    if vehiculos:
        if request.method == 'POST':
            form = RepostajeForm(request.POST, request.FILES)
            if form.is_valid():
                instancia = form.save(commit=False)

                aplica_descuento = form.cleaned_data['aplica_descuento']

                if aplica_descuento:
                    instancia.descuento = float(instancia.importe) * 0.03
                else:
                    instancia.descuento = 0.0

                instancia.importe = float(instancia.importe) - instancia.descuento

                if instancia.litros > 0:
                    instancia.precioxlitro = round(instancia.importe / float(instancia.litros), 2)
                else:
                    instancia.precioxlitro = 0

                # lee todos los repostajes del vehículo
                # repostajes = Repostajes.query.filter_by(vehiculo_id=vehiculo_id).all()

                if Repostaje.objects.filter(vehiculo_id=instancia.vehiculo):
                    repostajes = Repostaje.objects.filter(vehiculo_id=instancia.vehiculo).order_by('-fecha')[0]

                    instancia.kmsrecorridos = instancia.kms - repostajes.kms

                    if instancia.kmsrecorridos > 0:
                        instancia.consumo = round(instancia.litros * 100 / instancia.kmsrecorridos, 2)
                else:
                    instancia.kmsrecorridos = 0
                    instancia.consumo = 0

                instancia.save()

                return redirect('repostajes:lista_repostajes')
        else:
            form = RepostajeForm()
        return render(request, 'repostajes/form_repostaje.html', {'form': form})
    else:
        return render(request, 'repostajes/index.html')


@login_required
def editar_repostaje(request, repostaje_id):
    repostaje = get_object_or_404(Repostaje, pk=repostaje_id)

    if request.method == 'POST':
        form = RepostajeForm(request.POST, request.FILES, instance=repostaje)
        if form.is_valid():
            form.save()
            return redirect('repostajes:lista_repostajes')
    else:
        form = RepostajeForm(instance=repostaje)
    return render(request, 'repostajes/form_repostaje.html', {'form': form})


@login_required
def eliminar_repostaje(request, repostaje_id):
    repostaje = Repostaje.objects.get(pk=repostaje_id)
    repostaje.delete()
    return redirect('repostajes:lista_repostajes')


@api_view(['GET'])
def api_lista_vehiculos(request):
    """Devuelve la lista de todos los vehiculos."""
    vehiculos = Vehiculo.objects.all()
    serializer = VehiculoSerializer(vehiculos, many=True)
    return Response(serializer.data)


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


@api_view(['GET'])
def api_lista_repostajes(request):
    """Devuelve la lista de todos los repostajes."""
    repostajes = Repostaje.objects.all()
    serializer = RepostajeSerializer(repostajes, many=True)
    return Response(serializer.data)


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