# Path: project/apps/chinup/models.py
# class Metric(models.Model):
#     name = models.CharField(max_length=100)
#     description_worst = models.TextField(null=True, blank=True)
#     description_best = models.TextField(null=True, blank=True)
#     daily = models.BooleanField(default=True)
#     monthly = models.BooleanField(default=False)
#     boolean = models.BooleanField(default=False)
# 
#     def how_often_string(self):
#         if self.daily:
#             return "daily"
# 
#         if self.monthly:
#             return "monthly"
# 
#     def is_boolean_string(self):
#         if self.boolean:
#             return "boolean"
#         else:
#             return ""
# 
#     def average_span(self, day_span=30):
#         avg = MetricRecord.objects.filter(
#             metric=self,
#             datetime__gt=datetime.datetime.today() - timedelta(days=day_span),
#             datetime__lt=datetime.datetime.today()
#         ).aggregate(models.Avg('measurement'))
# 
#         return avg['measurement__avg']
# 
#     def __unicode__(self):
#         return "%s (%s) %s" % (self.name, self.how_often_string(), self.is_boolean_string())
# 
# class MetricRecord(models.Model):
#     metric = models.ForeignKey(Metric, unique_for_date="datetime")
#     datetime = models.DateField()
#     measurement = models.IntegerField(default=5, blank=True)
#     notes = models.TextField(null=True, blank=True)
# 
#     def save(self, *args, **kwargs):
#         # Boolean should default to 0, not 5!
#         if self.pk is None and self.metric.boolean:
#             self.measurement = 0
# 
#         super(MetricRecord, self).save(*args, **kwargs)
# 
#     def __unicode__(self):
#         return "Record for %s %s on %s" % (self.measurement, self.metric.name, self.datetime)


import datetime
import json
from datetime import timedelta
from dateutil import parser
from django.db.models import Avg
from django.http import HttpResponse
from django.shortcuts import render
from .models import Metric, MetricRecord
    metrics = Metric.objects.all()

    if day_of_month != 1:
        # Not first day of month, so filter out monthly
        metrics = Metric.objects.filter(daily=True, monthly=False)

    metric_records = [MetricRecord.objects.get_or_create(datetime=date, metric=m)[0] for m in metrics]
    metric_records_pks = [m.pk for m in metric_records]

    if request.method == "POST":
        data = json.loads(request.body)

        for metric_pk, value in data.items():
            # Make sure we aren't editing something we dont mean to, like if we didnt refresh the page since yesterday
            # it will only be working with datetime=today() by default
            if int(metric_pk) in metric_records_pks:
                for m in metric_records:
                    if m.pk == int(metric_pk):
                        m.notes = value.get('notes', None)
                        m.measurement = value['measurement']
                        m.save()

        return HttpResponse(status=200)

    return render(request, 'chinup/input.html', {
        'daily_checklist': [m for m in metric_records if m.metric.daily and m.metric.boolean],
        'daily_metrics': [m for m in metric_records if m.metric.daily and not m.metric.boolean],
        'monthly_metrics': [m for m in metric_records if m.metric.monthly],
        'day_of_month': day_of_month,
        'date': date,

# Path: project/apps/chinup/models.py
# class Metric(models.Model):
#     name = models.CharField(max_length=100)
#     description_worst = models.TextField(null=True, blank=True)
#     description_best = models.TextField(null=True, blank=True)
#     daily = models.BooleanField(default=True)
#     monthly = models.BooleanField(default=False)
#     boolean = models.BooleanField(default=False)
# 
#     def how_often_string(self):
#         if self.daily:
#             return "daily"
# 
#         if self.monthly:
#             return "monthly"
# 
#     def is_boolean_string(self):
#         if self.boolean:
#             return "boolean"
#         else:
#             return ""
# 
#     def average_span(self, day_span=30):
#         avg = MetricRecord.objects.filter(
#             metric=self,
#             datetime__gt=datetime.datetime.today() - timedelta(days=day_span),
#             datetime__lt=datetime.datetime.today()
#         ).aggregate(models.Avg('measurement'))
# 
#         return avg['measurement__avg']
# 
#     def __unicode__(self):
#         return "%s (%s) %s" % (self.name, self.how_often_string(), self.is_boolean_string())
# 
# class MetricRecord(models.Model):
#     metric = models.ForeignKey(Metric, unique_for_date="datetime")
#     datetime = models.DateField()
#     measurement = models.IntegerField(default=5, blank=True)
#     notes = models.TextField(null=True, blank=True)
# 
#     def save(self, *args, **kwargs):
#         # Boolean should default to 0, not 5!
#         if self.pk is None and self.metric.boolean:
#             self.measurement = 0
# 
#         super(MetricRecord, self).save(*args, **kwargs)
# 
#     def __unicode__(self):
#         return "Record for %s %s on %s" % (self.measurement, self.metric.name, self.datetime)


# Path: project/apps/chinup/views.py
import datetime
import json
from datetime import timedelta
from dateutil import parser
from django.db.models import Avg
from django.http import HttpResponse
from django.shortcuts import render
from .models import Metric, MetricRecord

    metrics = Metric.objects.all()

    if day_of_month != 1:
        # Not first day of month, so filter out monthly
        metrics = Metric.objects.filter(daily=True, monthly=False)

    metric_records = [MetricRecord.objects.get_or_create(datetime=date, metric=m)[0] for m in metrics]
    metric_records_pks = [m.pk for m in metric_records]

    if request.method == "POST":
        data = json.loads(request.body)

        for metric_pk, value in data.items():
            # Make sure we aren't editing something we dont mean to, like if we didnt refresh the page since yesterday
            # it will only be working with datetime=today() by default
            if int(metric_pk) in metric_records_pks:
                for m in metric_records:
                    if m.pk == int(metric_pk):
                        m.notes = value.get('notes', None)
                        m.measurement = value['measurement']
                        m.save()

        return HttpResponse(status=200)

    return render(request, 'chinup/input.html', {
        'daily_checklist': [m for m in metric_records if m.metric.daily and m.metric.boolean],
        'daily_metrics': [m for m in metric_records if m.metric.daily and not m.metric.boolean],
        'monthly_metrics': [m for m in metric_records if m.metric.monthly],
        'day_of_month': day_of_month,
        'date': date,

        'yesterday_link': date - timedelta(days=1),