# Path: holodeck/models.py
# class Dashboard(models.Model):
#     name = models.CharField(max_length=255)
#     owner = models.ForeignKey(User, null=True)
#     share_key = models.CharField(
#         max_length=32,
#         unique=True,
#         blank=True,
#         null=True
#     )
# 
#     def save(self, *args, **kwargs):
#         if not self.share_key:
#             self.share_key = generate_key()
#         super(Dashboard, self).save(*args, **kwargs)
# 
#     def __unicode__(self):
#         return self.name
# 
# Path: holodeck/widgets.py
# class LineChart(Widget):
#     name = 'Line Chart'
#     template_name = 'holodeck/widgets/line_chart.html'
#     width = 8
# 
#     def get_context(self, metric):
#         context = {
#             'metric': metric,
#             'width': self.width,
#         }
# 
#         groups = self.get_groups(metric)
# 
#         if not groups:
#             context['no_samples'] = True
#             return context
# 
#         grouped_samples = []
#         group_maxes = []
#         sample_count = 20
#         for group in groups:
#             samples = [(int(time.mktime(sample.timestamp.timetuple()) * 1000),
#                         sample.integer_value)
#                        for sample in metric.sample_set.filter(
#                            string_value=group
#                        ).order_by('-timestamp')[:sample_count]]
#             grouped_samples.append((group, samples))
#             group_maxes.append(max([sample[1] for sample in samples]))
#         samples = json.dumps([{'label': group[0], 'data': group[1]}
#                               for group in grouped_samples])
# 
#         context.update({
#             'samples': samples,
#             'y_max': max(group_maxes) * 1.025,
#         })
#         return context
# 
# class SampleDeviation(Widget):
#     name = 'Sample Deviation'
#     template_name = 'holodeck/widgets/sample_deviation.html'
#     width = 4
# 
#     def calc_deviation(self, primary, secondary):
#         if secondary == 0:
#             return primary * 100
#         return int((primary * 100.0) / secondary) - 100
# 
#     def gen_deviation(self, primary, secondary):
#         dev = self.calc_deviation(primary, secondary)
#         color = 'green'
#         if dev >= -10 and dev <= 10:
#             color = 'orange'
#         if dev < -10:
#             color = 'red'
#         return {
#             'percentage': '%s%s' % ('+' if dev > 0 else '', dev),
#             'color': color
#         }
# 
#     def get_context(self, metric):
#         from django.db.models import Avg, Max
#         context = {
#             'metric': metric,
#             'width': self.width,
#         }
# 
#         try:
#             current = metric.sample_set.all().order_by(
#                 '-timestamp')[0].integer_value
#         except IndexError:
#             context['no_samples'] = True
#             return context
# 
#         try:
#             previous = metric.sample_set.all().order_by(
#                 '-timestamp')[1].integer_value
#         except IndexError:
#             previous = 0
# 
#         average = int(metric.sample_set.all().aggregate(
#             Avg('integer_value'))['integer_value__avg'])
#         peak = int(metric.sample_set.all().aggregate(
#             Max('integer_value'))['integer_value__max'])
# 
#         context.update({
#             'current': current,
#             'previous': self.gen_deviation(current, previous),
#             'average': self.gen_deviation(current, average),
#             'peak': self.gen_deviation(current, peak),
#         })
# 
#         return context


from copy import copy
from django import template
from holodeck.models import Dashboard
from holodeck.widgets import LineChart, SampleDeviation


register = template.Library()


@register.inclusion_tag('holodeck/inclusion_tags/dashboard_dropdown.html', takes_context=True)
def dashboard_dropdown(context):
    context.update({
        'dashboard_list': Dashboard.objects.all().order_by('name')
    })
    return context


@register.inclusion_tag('holodeck/inclusion_tags/render_metric.html', takes_context=True)
def render_metric(context, metric, minimal=False):
    context = copy(context)
    return {'result': metric.render(context, minimal)}


@register.inclusion_tag('holodeck/inclusion_tags/dashboard_list_summary.html')
def dashboard_list_summary(dashboard):
    context = {
        'dashboard': dashboard,
    }

    metrics = dashboard.metric_set.filter(
        widget_type='holodeck.widgets.LineChart'
    )

    sampled_metric = None

# Path: holodeck/models.py
# class Dashboard(models.Model):
#     name = models.CharField(max_length=255)
#     owner = models.ForeignKey(User, null=True)
#     share_key = models.CharField(
#         max_length=32,
#         unique=True,
#         blank=True,
#         null=True
#     )
# 
#     def save(self, *args, **kwargs):
#         if not self.share_key:
#             self.share_key = generate_key()
#         super(Dashboard, self).save(*args, **kwargs)
# 
#     def __unicode__(self):
#         return self.name
# 
# Path: holodeck/widgets.py
# class LineChart(Widget):
#     name = 'Line Chart'
#     template_name = 'holodeck/widgets/line_chart.html'
#     width = 8
# 
#     def get_context(self, metric):
#         context = {
#             'metric': metric,
#             'width': self.width,
#         }
# 
#         groups = self.get_groups(metric)
# 
#         if not groups:
#             context['no_samples'] = True
#             return context
# 
#         grouped_samples = []
#         group_maxes = []
#         sample_count = 20
#         for group in groups:
#             samples = [(int(time.mktime(sample.timestamp.timetuple()) * 1000),
#                         sample.integer_value)
#                        for sample in metric.sample_set.filter(
#                            string_value=group
#                        ).order_by('-timestamp')[:sample_count]]
#             grouped_samples.append((group, samples))
#             group_maxes.append(max([sample[1] for sample in samples]))
#         samples = json.dumps([{'label': group[0], 'data': group[1]}
#                               for group in grouped_samples])
# 
#         context.update({
#             'samples': samples,
#             'y_max': max(group_maxes) * 1.025,
#         })
#         return context
# 
# class SampleDeviation(Widget):
#     name = 'Sample Deviation'
#     template_name = 'holodeck/widgets/sample_deviation.html'
#     width = 4
# 
#     def calc_deviation(self, primary, secondary):
#         if secondary == 0:
#             return primary * 100
#         return int((primary * 100.0) / secondary) - 100
# 
#     def gen_deviation(self, primary, secondary):
#         dev = self.calc_deviation(primary, secondary)
#         color = 'green'
#         if dev >= -10 and dev <= 10:
#             color = 'orange'
#         if dev < -10:
#             color = 'red'
#         return {
#             'percentage': '%s%s' % ('+' if dev > 0 else '', dev),
#             'color': color
#         }
# 
#     def get_context(self, metric):
#         from django.db.models import Avg, Max
#         context = {
#             'metric': metric,
#             'width': self.width,
#         }
# 
#         try:
#             current = metric.sample_set.all().order_by(
#                 '-timestamp')[0].integer_value
#         except IndexError:
#             context['no_samples'] = True
#             return context
# 
#         try:
#             previous = metric.sample_set.all().order_by(
#                 '-timestamp')[1].integer_value
#         except IndexError:
#             previous = 0
# 
#         average = int(metric.sample_set.all().aggregate(
#             Avg('integer_value'))['integer_value__avg'])
#         peak = int(metric.sample_set.all().aggregate(
#             Max('integer_value'))['integer_value__max'])
# 
#         context.update({
#             'current': current,
#             'previous': self.gen_deviation(current, previous),
#             'average': self.gen_deviation(current, average),
#             'peak': self.gen_deviation(current, peak),
#         })
# 
#         return context


# Path: holodeck/templatetags/holodeck_inclusion_tags.py
from copy import copy
from django import template
from holodeck.models import Dashboard
from holodeck.widgets import LineChart, SampleDeviation



register = template.Library()


@register.inclusion_tag('holodeck/inclusion_tags/dashboard_dropdown.html', takes_context=True)
def dashboard_dropdown(context):
    context.update({
        'dashboard_list': Dashboard.objects.all().order_by('name')
    })
    return context


@register.inclusion_tag('holodeck/inclusion_tags/render_metric.html', takes_context=True)
def render_metric(context, metric, minimal=False):
    context = copy(context)
    return {'result': metric.render(context, minimal)}


@register.inclusion_tag('holodeck/inclusion_tags/dashboard_list_summary.html')
def dashboard_list_summary(dashboard):
    context = {
        'dashboard': dashboard,
    }

    metrics = dashboard.metric_set.filter(
        widget_type='holodeck.widgets.LineChart'
    )

    sampled_metric = None

    for metric in metrics: