import http
import logging
from datetime import datetime

from django.views.generic import View
from django.http import JsonResponse

from events.models import Event

logger = logging.getLogger(__name__)

from timer.models import TimeRecord


class WriteTimeApiView(View):
    """
    View to write time records
    create a new TimeRecord object with the given parameters and save it to the database
    returns standard JsonResponse with status 'ok' if successful or error message if not
    """
    @staticmethod
    def get(request, *args, **kwargs):
        try:

            # parse datetime from string of unix timestamp with milliseconds '1741169756.049847'
            record_time = datetime.fromtimestamp(float(kwargs['time']))

            # create new TimeRecord object and save it to the database
            TimeRecord(
                card_id=kwargs['card_id'],
                timer_id=kwargs['timer_id'],
                time=record_time,
            ).save()

            # find the active event
            event = Event.objects.filter(
                is_active=True,
            )

            # if there is no active event, log error
            if not event:
                logger.error("No active event found")
                return JsonResponse({"error": "No active event found"}, status=http.HTTPStatus.NOT_FOUND, safe=False)

            # find registration with the given card_id
            registration = event[0].registrations.filter(
                card_id=kwargs['card_id'],
            )
            if not registration:
                logger.error(f"No registration found for card_id: {kwargs['card_id']}")
                return JsonResponse({"status": "ok"}, status=http.HTTPStatus.OK ,safe=False)

            # if there is more than one registration with the same card_id, log error
            if len(registration) > 1:
                logger.error(f"Multiple registrations found for card_id: {kwargs['card_id']}")

            # create new lap or update existing lap
            registration[0].laps.filter(end = None).update(end = record_time)



            return JsonResponse({"status": "ok"}, status=http.HTTPStatus.OK ,safe=False)
        except Exception as e:
            logger.error(f"Error while getting prometheus data: {e}")
            return JsonResponse({"error": f"Error while getting prometheus data: {e}"}, status=http.HTTPStatus.INTERNAL_SERVER_ERROR , safe=False)