#from django.shortcuts import render
from django.core.exceptions import *
import MySQLdb
#from reader import models
from .models import Readings, Beer, TemperatureProfile
from .forms import GranularityForm
import datetime
import time
#from datetime import datetime, timedelta

# Create your views here.
import os
from decimal import Decimal
from datetime import timedelta
os.environ['MPLCONFIGDIR'] = '/home/sean/data'
from django.http import HttpResponse
#import numpy as np  # (*) numpy for math functions and arrays
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
#import cStringIO
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

from django.template import RequestContext, loader
from django.shortcuts import render, get_object_or_404, render_to_response
from django.http import Http404
from django.views import generic
from django.utils import timezone

class IndexView(generic.ListView):
    template_name = 'beerviewer/index.html'
    context_object_name = 'reading_list'
    

    def get_queryset(self):
        return Beer.objects.order_by('-id')


#def index(request):    
#    reading_list = Beer.objects.order_by('-id')   
#    context = RequestContext(request, {
#        'reading_list': reading_list,
#    })
#    return render(request, 'reader/index.html', context)
records_per_minute = 12
#def status(request):
#    f = open("/home/pi/data/readings.csv", 'r')    
#    return HttpResponse("The data is : " +  "<br />".join(f.read().split("\n")))
    #return HttpResponse("You got to the status data bro!")

def getLatestBeer(request):
    data = Readings.objects.order_by('-id')[:5]
    output = ','.join([str(p.id) for p in data])
    return HttpResponse(output)

def details(request, id):     
    try:
        db = MySQLdb.connect(host="localhost", # your host, usually localhost
                                user="root", # your username
                                passwd="unbr34k4b73", # your password
                                db="testdb") # name of the data base

        # you must create a Cursor object. It will let
        #  you execute all the queries you need
        cur = db.cursor() 
        cur.execute("SELECT * from reader_readings where id = " + id)
        row = cur.fetchone()
        response = HttpResponse("For ID " + str(id) + " the results are " + str(row[0]) + "," + str(row[1]) + "," + str(row[2]) + "," + str(row[3]) + "," + str(row[4]))
        cur.close()
        db.close()
        return response;
    except:
        raise Http404("ID" + str(id) + " does not exist")             

def beerDetailChooser(request, beerName):
    beer = ""
    output = ""
    try:
        beer = Beer.objects.get(name=beerName)
    except Beer.DoesNotExist:
        output = "No beer " + beerName + " found";
    except MultipleObjectsReturned:
        output = "More than one beer " + beerName + " found";
    if(beer):
        output = "Found a beer by " + beerName
        
        output = output + " And granularity was "
        if request.method == 'POST':
        # create a form instance and populate it with data from the request:
            form = GranularityForm(request.POST)
            # check whether it's valid:
            if form.is_valid():
                # process the data in form.cleaned_data as required
                # ...
                # redirect to a new URL:
                output = output + " Successfully got granularity for real of " + str(form.cleaned_data['granularity'])
                return generateGraphWithRange(beer, 
                                             form.cleaned_data['granularity'], 
                                             form.cleaned_data['start_time'],
                                             form.cleaned_data['end_time'])

    # if a GET (or any other method) we'll create a blank form
        else:
            end_time = beer.end_time
            if not end_time:
                #Not defined, use right now
                end_time = datetime.datetime.utcnow()
            form = GranularityForm(initial={'end_time' : end_time,
                                            'start_time' : beer.start_time})

    #return render(request, 'name.html', {'form': form})
        #Now that we have a valid beer object, get the start and end date
        #return generateGraph(beer, granularity, 65, 68)
    context = RequestContext(request, {
        'beer': beer,
        'form': form,
    })
    return render(request, 'beerviewer/detailchooser.html', context)

def feed(request, beerName):
    return render(request, 'beerviewer/feed.html')

def generateGraphWithRange(beer, 
                           granularity, 
                           start, 
                           end,
                           xwidth=20,
                           ywidth=12):
    records = Readings.objects.mod(start, end, records_per_minute*granularity)
    #output = "Found " + str(records.count()) + " records in the table"
    dates  = []        
    primarytemp = []
    mintemp = []
    maxtemp = []
    heat_start = -1
    cooling_start = -1
    
    fig = plt.figure(figsize=(xwidth,ywidth), dpi=80)
    ax = fig.add_subplot(111)
    colorings = []
    for curt in records:
        dates.append(curt[0])
        primarytemp.append(curt[1])
        if(curt[2] == 1 and heat_start == -1):
            #Heating state turned on
            heat_start = curt[0]