#!/usr/bin/env python

from datetime import datetime
import sys
import MySQLdb

device = "ref_davis"

rain = []
temp = []
wind = []
pressure = []

def index(req):
        try:
                conn = MySQLdb.connect(host="localhost",
                        user="glacsweb-ro",
                        passwd="iceland",
                        db="iceland");
                cursor = conn.cursor()
		cursor.execute("SELECT DATE(timestamp) , sum( value ) FROM `rain_readings` WHERE `device_id` LIKE '%s' GROUP BY DATE( timestamp );" %device)
		rain = cursor.fetchall()
		cursor.execute("SELECT timestamp, ROUND(AVG(speed),1), ROUND(AVG(direction),0)  FROM `wind_readings` WHERE device_id LIKE '%s' GROUP BY DATE(timestamp), HOUR(timestamp);" % device)
		wind = cursor.fetchall()
		temp = cursor.execute("SELECT t.timestamp, ROUND(AVG(t.value),1) AS temp, ROUND(AVG(h.value),1)  FROM `temperature_readings` AS t, humidity_readings AS h WHERE t.device_id LIKE '%s' AND t.device_id = h.device_id AND t.timestamp = h.timestamp AND t.sensor_position_id = 2 GROUP BY DATE(t.timestamp), HOUR(t.timestamp);" % device)
		temp = cursor.fetchall()
		cursor.execute("SELECT timestamp, ROUND(AVG(value), 3) FROM pressure_readings WHERE device_id ='%s' GROUP BY DATE(timestamp), HOUR(timestamp);" % device)
		pressure = cursor.fetchall()
		cursor.close()
                conn.commit()
                conn.close()
        except MySQLdb.Error, e:
                print "Error %d: %s" % (e.args[0], e.args[1])
                sys.exit(1)
        output = """
<html>
<head>
<title> Glacsweb Davis Weather Station Data </title>
<script type="text/javascript"
  src="dygraph-combined.js"></script>
</head>
<body>
<h1> Glacsweb Davis Weather Station Data </h1>
<p>The data shown here is sampled every minute but for the purpose of these graphs has been agregated to hourly averages for all readings except rainfall, which has been converted to a daily total.</p>
<p>To zoom on the graph highlight the region you would like to zoom in on, this works with both the X and Y axis.  To return the graph to showing all data double click on it</p>
<h2> Daily Rain Fall (mm)</h2>
<div id="raindiv"></div>
<script type="text/javascript">
  g = new Dygraph(
    document.getElementById("raindiv"),
        """
        i = 0
        m = len(rain)
        while i < m:
        	output += "\"%s,%s\\n\"" %(rain[i][0], rain[i][1])
                if i <  m-1:
			output += "+\n"
		else:
			output += "\n"
		i = i+1
        output += """,{
                labels: ["Date", "Daily Rain"],
                legend: "always",
		height: 600,
                width: 800,
                }
         );
</script>"""

	output +="<h2>Average Hourly Wind Speed km/h</h2>\n"

	output += """
<div id="winddiv"></div>
<script type="text/javascript">
  g = new Dygraph(
    document.getElementById("winddiv"),
        """
        i = 0
        m = len(wind)
        while i < m:
                output += "\"%s,%s,%s\\n\"" %(wind[i][0], wind[i][1], wind [i][2])
                if i <  m-1:
                        output += "+\n"
                else:
                        output += "\n"
                i = i+1
        output += """,{
                labels: ["Date", "Wind Speed", "Wind Direction"],
                height: 600,
                width: 800,
		legend: "always",
		'Wind Speed':{
			axis:{}
		},
		'Wind direction':{
			axis:{}
		},
		}
         );
</script>
<h2>Temperature and Humidity</h2>
<div id="tempdiv"></div>
<script type="text/javascript">
  g = new Dygraph(
    document.getElementById("tempdiv"),
        """
        i = 0
        m = len(temp)
        while i < m:
                output += "\"%s,%s,%s\\n\"" %(temp[i][0], temp[i][1], temp [i][2])
                if i <  m-1:
                        output += "+\n"
                else:
                        output += "\n"
                i = i+1
        output += """,{
                labels: ["Date", "Temperature", "Humidity"],
                height: 600,
                width: 800,
		lengend: "always",
		'Temperature':{
			axis:{label:"Temperature"}
		},
		}
	);
</script>
<h2>Pressure</h2>
<div id="pressurediv"></div>
<script type="text/javascript">
  g = new Dygraph(
    document.getElementById("pressurediv"),
"""
	i = 0
	m = len(pressure)
	while i < m:
		output +="\"%s,%s\\n\"" %(pressure[i][0], pressure[i][1])
		if i < m-1:
			output += "+\n"
                else:
                        output += "\n"
                i = i+1
	output += """,{
		labels: ["Date", "Pressure"],
		height: 600,
		width:	800,
		legend: "always",
		xlabel: "Date",
		ylabel: "Pressure mbar",
		}
	);
</script>
</body>
</html>
"""
	return output
