from django.shortcuts import render
from main.models import alarmierung, alarmierung_SW, fahrzeug
from datetime import timedelta
from django.utils import timezone
import ast

# Create your views here.
def index(request):
    now = timezone.now()
    fifteen_minutes_ago = now - timedelta(minutes=10)
    fifteen_seconds_ago = now - timedelta(seconds=15)
    alarm_request = alarmierung.objects.filter(timestamp__gte=fifteen_minutes_ago).order_by("-timestamp").values_list()[0] if alarmierung.objects.filter(timestamp__gte=fifteen_minutes_ago).values_list().__len__() > 0 else None
    if alarm_request != None:
        alarm_request = alarm_request[:2] + (alarmierung_SW.objects.get(id=int(alarm_request[2])).kürzel,) + alarm_request[3:]
        fz_list = []
        print(alarm_request[4])
        for i in ast.literal_eval(alarm_request[4]):
            fz = fahrzeug.objects.get(id=int(i))
            fz_list.append(fz.Funkrufname + " - " + fz.kürzel)
        alarm_request = alarm_request[:4] + (fz_list,)
        if now - alarm_request[1] > timedelta(seconds=25):
            alarm_request = alarm_request[:5] + (False,)
        else:
            alarm_request = alarm_request[:5] + (True,)


    return render(request, 'monitor/index.html', {'alarm':alarm_request})