from datetime import timedelta
import json

from django.shortcuts import redirect, render
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django.utils import timezone

from . import models
from . import forms


@require_http_methods(["GET"])
def index(request):
    return render(request, 'medwings/index.html')


@login_required
@require_http_methods(["GET"])
def dashboard(request):
    mews_records = models.MewsRecord.objects.filter(user=request.user)
    blood_pressure_records = models.BloodPressureRecord.objects.filter(user=request.user)
    body_temp_records = models.BodyTempRecord.objects.filter(user=request.user)
    heart_rate_records = models.HeartRateRecord.objects.filter(user=request.user)
    spo2_level_records = models.Spo2LevelRecord.objects.filter(user=request.user)
    respiration_score_records = models.RespirationScoreRecord.objects.filter(user=request.user)

    context = {
        "mews_data": json.dumps([{"x": record.recorded.timestamp(), "y": record.value_n} for record in mews_records]),
        "blood_pressure_data": json.dumps([{"x": record.recorded.timestamp(), "y": record.value_systolic_mmhg} for record in blood_pressure_records]),
        "body_temp_data": json.dumps([{"x": record.recorded.timestamp(), "y": float(record.value_celsius)} for record in body_temp_records]),
        "heart_rate_data": json.dumps([{"x": record.recorded.timestamp(), "y": record.value_bpm} for record in heart_rate_records]),
        "spo2_level_data": json.dumps([{"x": record.recorded.timestamp(), "y": record.value_percent} for record in spo2_level_records]),
        "respiration_score_data": json.dumps([{"x": record.recorded.timestamp(), "y": record.value_severity} for record in respiration_score_records]),
    }

    return render(request, 'medwings/dashboard.html', context)


@login_required
@require_http_methods(["GET", "POST"])
def mews_init(request):
    if request.method == 'POST':
        respiration_score_form = forms.RespirationScoreForm(request.POST)

        if respiration_score_form.is_valid():
            respiration_score = respiration_score_form.save(commit=False)
            respiration_score.recorded = timezone.now()
            respiration_score.user = request.user
            respiration_score.save()

            return redirect('mews-continue')

    else:
        respiration_score_form = forms.RespirationScoreForm()

    context = {
        'respiration_score_form': respiration_score_form,
    }

    return render(request, 'medwings/mews-init.html', context)


@login_required
def mews_continue(request):
    return render(request, 'medwings/mews-continue.html')


@require_http_methods(["GET"])
def mews_status(request):
    if not request.user.is_authenticated:
        return HttpResponse('Unauthorized', status=401)

    request.user.apiaccount.update_records()
    
    ten_minutes_ago = timezone.now() - timedelta(minutes=10)
    blood_pressure_record = models.BloodPressureRecord.objects.filter(user=request.user).filter(recorded__gte=ten_minutes_ago).order_by('-recorded').first()
    body_temp_record = models.BodyTempRecord.objects.filter(user=request.user).filter(recorded__gte=ten_minutes_ago).order_by('-recorded').first()
    heart_rate_record = models.HeartRateRecord.objects.filter(user=request.user).filter(recorded__gte=ten_minutes_ago).order_by('-recorded').first()
    spo2_level_record = models.Spo2LevelRecord.objects.filter(user=request.user).filter(recorded__gte=ten_minutes_ago).order_by('-recorded').first()
    respiration_score_record = models.RespirationScoreRecord.objects.filter(user=request.user).filter(recorded__gte=ten_minutes_ago).order_by('-recorded').first()

    data = {
        'blood_pressure_value': blood_pressure_record.value_systolic_mmhg if blood_pressure_record else None,
        'body_temp_value': body_temp_record.value_celsius if body_temp_record else None,
        'heart_rate_value': heart_rate_record.value_bpm if heart_rate_record else None,
        'spo2_level_value': spo2_level_record.value_percent if spo2_level_record else None,
        'respiration_score_value': respiration_score_record.value_severity if respiration_score_record else None,
        'mews_value': None,
    }

    if (blood_pressure_record
        and body_temp_record
        and heart_rate_record
        and spo2_level_record
        and respiration_score_record
    ):
        mews_record = models.MewsRecord(
            user=request.user, recorded=timezone.now(),
            value_n=models.MewsRecord.calculate_mews_value(
                blood_pressure_record.value_systolic_mmhg,
                body_temp_record.value_celsius,
                heart_rate_record.value_bpm,
                spo2_level_record.value_percent,
                respiration_score_record.value_severity
            ),
            blood_pressure_record=blood_pressure_record,
            body_temp_record=body_temp_record,
            heart_rate_record=heart_rate_record,
            respiration_score_record=respiration_score_record,
            spo2_level_record=spo2_level_record
        )
        mews_record.save()
        data['mews_value'] = mews_record.value_n

    return JsonResponse(data)
