from flask import render_template, redirect, request, session
from flask import jsonify
from flask_login import login_required
from app import app, db
from .models import MeasurementType, Measurement
import re
import datetime


@app.route('/', methods=['GET'])
@login_required
def dashboard_index():
    payload = None
    types = MeasurementType.query.all()
    now = datetime.datetime.now()
    past = now - datetime.timedelta(minutes=60)
    for t in types:
        dataset = [t.id, t.name, None, [], []]

        recent = Measurement.query.filter(Measurement.type_id == t.id, Measurement.date_time > past).order_by(Measurement.date_time.asc())
        if not recent:
            continue

        dataset[2] = recent[-1].simplified()
        for d in recent:
            dataset[3].append(datetime.datetime.strftime(d.date_time, "%m/%d/%y %H:%M"))
            dataset[4].append(d.value)

        if not payload:
            payload = []

        payload.append(dataset)

    return render_template('measurement/index.html', 
                title='Environment',
                payload=payload)


@app.route('/measurement_type/<pk>/latest', methods=['GET'])
def measurement_latest(pk):
    mt = MeasurementType.query.get_or_404(int(pk))
    latest = Measurement.query.filter(Measurement.type_id == mt.id).order_by(Measurement.date_time.desc()).first()
    return jsonify(latest.simplified())






@@ -641,24 +641,25 @@
 .asc())%0A
+%0A
         
 if not r
@@ -654,45 +654,17 @@
     
-if not recent
+try
 :%0A    
-        continue%0A%0A
     
@@ -708,24 +708,28 @@
 d()%0A        
+  
+  
 for d in rec
@@ -733,16 +733,20 @@
 recent:%0A
+    
         
@@ -830,32 +830,36 @@
 %22))%0A            
+    
 dataset%5B4%5D.appen
@@ -878,16 +878,20 @@
         
+ 
+   
 if not p
@@ -906,24 +906,28 @@
             
+    
 payload = %5B%5D
@@ -928,16 +928,20 @@
 d = %5B%5D%0A%0A
+    
         
@@ -963,16 +963,49 @@
 dataset)
+%0A        except:%0A            pass
 %0A%0A    re
@@ -1379,16 +1379,56 @@
 first()%0A
+    if not latest:%0A        return None%0A%0A
     retu

fix to measurement view for index/dashboard