import http
import logging
from datetime import datetime
from django.utils import timezone
from django.views.generic import View
from django.http import JsonResponse

from events.models import Event, Lap

logger = logging.getLogger(__name__)

from timer.models import TimeRecord


class HealthCheckApiView(View):
    """
    View to check if the server is running
    returns standard JsonResponse with status 'ok'
    """
    @staticmethod
    def get(request, *args, **kwargs):
        return JsonResponse({"status": "ok"}, status=http.HTTPStatus.OK, safe=False)


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 = timezone.make_aware(datetime.fromtimestamp(float(kwargs['time'])))

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

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

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

            # find registration with the given card_id
            registration = event[0].registrations.filter(
                chip_id=kwargs['chip_id'],
            )

            if not registration:
                logger.error(f"No registration found for chip_id: {kwargs['chip_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 chip_id: {kwargs['chip_id']}")

            # create new lap or update existing lap
            laps = Lap.objects.filter(registration=registration[0])
            open_lap = laps.filter(end=None)
            if not open_lap:
                registration[0].laps.create(
                    start=record_time,
                    number=len(laps) + 1,
                )
            else:
                open_lap[0].end = record_time
                open_lap[0].save()

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