# Path: console/forms.py
# class CalendarForm(forms.Form):
#     year = forms.IntegerField()
#     month = forms.ChoiceField(
#         required=False,
#         widget=SelectAutocomplete(plugin_options={"width": "200px"}),
#         choices=[('', '')] + [(k, v) for k, v in MONTHS.items()])
#     day = forms.IntegerField(required=False)
# 
#     def __init__(self, *args, **kwargs):
#         super(CalendarForm, self).__init__(*args, **kwargs)
#         today = datetime.today()
#         yesterday = today - timedelta(1)
#         self.fields['year'].initial = yesterday.year
#         self.fields['month'].initial = yesterday.month
#         self.fields['day'].initial = yesterday.day
#         self.fields['day'].widget.attrs['min'] = 1
# 
#     def has_value(self, field):
#         data = self.cleaned_data
#         if field in data and data[field]:
#             return True
#         return False
# 
#     def get_params(self):
#         res = {}
#         data = self.cleaned_data
#         if self.has_value('year'):
#             res['year'] = data['year']
#         if self.has_value('month'):
#             res['month'] = int(data['month'])
#         if self.has_value('day'):
#             res['day'] = data['day']
#         return res
# 
#     def metric_name(self):
#         metric_name = ''
#         data = self.cleaned_data
#         if self.has_value('year'):
#             metric_name = str(data['year'])
#             if self.has_value('month'):
#                 metric_name = str(data['month']) + '-' + metric_name
#                 if self.has_value('day'):
#                     metric_name = str(data['day']) + '-' + metric_name
#         return metric_name
# 
#     def time_unit(self):
#         if self.has_value('day'):
#             return 'hour'
#         elif self.has_value('month'):
#             return 'day'
#         return 'month'
# 
#     def is_in_the_future(self):
#         data = self.get_params()
#         today = datetime.today()
#         if 'year' in data and data['year'] > today.year:
#             return True
#         if ('year' in data and data['year'] == today.year and
#            'month' in data and data['month'] > today.month):
#             return True
#         if ('year' in data and data['year'] == today.year and
#            'month' in data and data['month'] == today.month and
#            'day' in data and data['day'] > today.day):
#             return True
#         return False
# 
#     def clean(self):
#         data = super(CalendarForm, self).clean()
#         if self.has_value('day') and not self.has_value('month'):
#             self._errors['month'] = self.error_class(['Month is required.'])
#         if self.is_in_the_future():
#             raise forms.ValidationError('Set a date in the past.')
#         return data
# 
# class MetricDetailForm(forms.Form):
#     metric_url = forms.CharField()
#     metric_type = forms.CharField()
#     subject = forms.CharField()
# 
#     def clean(self):
#         cd = super(MetricDetailForm, self).clean()
#         if 'metric_url' in cd:
#             try:
#                 resolve(cd['metric_url'])
#             except Resolver404:
#                 raise forms.ValidationError('Invalid url')
#         return cd
# 
# Path: console/decorators.py
# def login_required(function):
#     def wrap(request, *args, **kwargs):
#         if (request.session.get('username', False) and
#            request.session.get('password', False) and
#            request.session.get('api_url', False)):
#             return function(request, *args, **kwargs)
#         else:
#             return HttpResponseRedirect('/')
# 
#     wrap.__doc__ = function.__doc__
#     wrap.__name__ = function.__name__
# 
#     return wrap
# 
# Path: console/views.py
# def main_render(request, template, v_dict={}):
#     username = request.session.get('username', False)
#     password = request.session.get('password', False)
#     api_url = request.session.get('api_url', False)
# 
#     if username and password and api_url:
#         client = CC(username, password, api_url)
# 
#         v_dict['containers'] = sorted(
#             client.containers().json(), key=lambda k: k['name'])
#         last_alarm = client.alarms({'range': 1}).json()
#         if last_alarm:
#             v_dict['last_alarm_id'] = last_alarm[0]['id']
# 
#     return render_to_response(
#         template, v_dict, context_instance=RequestContext(request))


import json
import re
from django.http import HttpResponse
from django.forms import ValidationError
from django.views.decorators.csrf import ensure_csrf_cookie
from uwsgiit.api import UwsgiItClient as UC
from .forms import CalendarForm, MetricDetailForm
from .decorators import login_required
from .views import main_render
                request.session.get('password'),
                request.session.get('api_url'))

    time_unit = 'hour'
    metric_name = 'Invalid date'
    stats = []
    if request.POST and request.is_ajax:
        calendar = CalendarForm(request.POST)
        if calendar.is_valid():
            params = calendar.get_params()
            metric_name = calendar.metric_name()
            time_unit = calendar.time_unit()
            stats = [metric.metrics(client, params) for metric in metrics]

    v_dict = {}
    v_dict['stats'] = stats
    v_dict['time_unit'] = time_unit
    v_dict['metric_name'] = metric_name
    v_dict['unit_of_measure'] = metrics[0].unit_of_measure
    v_dict['absolute_values'] = kwargs['absolute_values']
    v_dict['average'] = kwargs['average']
    return HttpResponse(json.dumps(v_dict))


@login_required
def container_metrics(request, container, **kwargs):
    metrics = [kwargs['model'](container=container)]
    return stats_render(request, metrics, **kwargs)



# Path: console/forms.py
# class CalendarForm(forms.Form):
#     year = forms.IntegerField()
#     month = forms.ChoiceField(
#         required=False,
#         widget=SelectAutocomplete(plugin_options={"width": "200px"}),
#         choices=[('', '')] + [(k, v) for k, v in MONTHS.items()])
#     day = forms.IntegerField(required=False)
# 
#     def __init__(self, *args, **kwargs):
#         super(CalendarForm, self).__init__(*args, **kwargs)
#         today = datetime.today()
#         yesterday = today - timedelta(1)
#         self.fields['year'].initial = yesterday.year
#         self.fields['month'].initial = yesterday.month
#         self.fields['day'].initial = yesterday.day
#         self.fields['day'].widget.attrs['min'] = 1
# 
#     def has_value(self, field):
#         data = self.cleaned_data
#         if field in data and data[field]:
#             return True
#         return False
# 
#     def get_params(self):
#         res = {}
#         data = self.cleaned_data
#         if self.has_value('year'):
#             res['year'] = data['year']
#         if self.has_value('month'):
#             res['month'] = int(data['month'])
#         if self.has_value('day'):
#             res['day'] = data['day']
#         return res
# 
#     def metric_name(self):
#         metric_name = ''
#         data = self.cleaned_data
#         if self.has_value('year'):
#             metric_name = str(data['year'])
#             if self.has_value('month'):
#                 metric_name = str(data['month']) + '-' + metric_name
#                 if self.has_value('day'):
#                     metric_name = str(data['day']) + '-' + metric_name
#         return metric_name
# 
#     def time_unit(self):
#         if self.has_value('day'):
#             return 'hour'
#         elif self.has_value('month'):
#             return 'day'
#         return 'month'
# 
#     def is_in_the_future(self):
#         data = self.get_params()
#         today = datetime.today()
#         if 'year' in data and data['year'] > today.year:
#             return True
#         if ('year' in data and data['year'] == today.year and
#            'month' in data and data['month'] > today.month):
#             return True
#         if ('year' in data and data['year'] == today.year and
#            'month' in data and data['month'] == today.month and
#            'day' in data and data['day'] > today.day):
#             return True
#         return False
# 
#     def clean(self):
#         data = super(CalendarForm, self).clean()
#         if self.has_value('day') and not self.has_value('month'):
#             self._errors['month'] = self.error_class(['Month is required.'])
#         if self.is_in_the_future():
#             raise forms.ValidationError('Set a date in the past.')
#         return data
# 
# class MetricDetailForm(forms.Form):
#     metric_url = forms.CharField()
#     metric_type = forms.CharField()
#     subject = forms.CharField()
# 
#     def clean(self):
#         cd = super(MetricDetailForm, self).clean()
#         if 'metric_url' in cd:
#             try:
#                 resolve(cd['metric_url'])
#             except Resolver404:
#                 raise forms.ValidationError('Invalid url')
#         return cd
# 
# Path: console/decorators.py
# def login_required(function):
#     def wrap(request, *args, **kwargs):
#         if (request.session.get('username', False) and
#            request.session.get('password', False) and
#            request.session.get('api_url', False)):
#             return function(request, *args, **kwargs)
#         else:
#             return HttpResponseRedirect('/')
# 
#     wrap.__doc__ = function.__doc__
#     wrap.__name__ = function.__name__
# 
#     return wrap
# 
# Path: console/views.py
# def main_render(request, template, v_dict={}):
#     username = request.session.get('username', False)
#     password = request.session.get('password', False)
#     api_url = request.session.get('api_url', False)
# 
#     if username and password and api_url:
#         client = CC(username, password, api_url)
# 
#         v_dict['containers'] = sorted(
#             client.containers().json(), key=lambda k: k['name'])
#         last_alarm = client.alarms({'range': 1}).json()
#         if last_alarm:
#             v_dict['last_alarm_id'] = last_alarm[0]['id']
# 
#     return render_to_response(
#         template, v_dict, context_instance=RequestContext(request))


# Path: console/views_metrics.py
import json
import re
from django.http import HttpResponse
from django.forms import ValidationError
from django.views.decorators.csrf import ensure_csrf_cookie
from uwsgiit.api import UwsgiItClient as UC
from .forms import CalendarForm, MetricDetailForm
from .decorators import login_required
from .views import main_render

                request.session.get('password'),
                request.session.get('api_url'))

    time_unit = 'hour'
    metric_name = 'Invalid date'
    stats = []
    if request.POST and request.is_ajax:
        calendar = CalendarForm(request.POST)
        if calendar.is_valid():
            params = calendar.get_params()
            metric_name = calendar.metric_name()
            time_unit = calendar.time_unit()
            stats = [metric.metrics(client, params) for metric in metrics]

    v_dict = {}
    v_dict['stats'] = stats
    v_dict['time_unit'] = time_unit
    v_dict['metric_name'] = metric_name
    v_dict['unit_of_measure'] = metrics[0].unit_of_measure
    v_dict['absolute_values'] = kwargs['absolute_values']
    v_dict['average'] = kwargs['average']
    return HttpResponse(json.dumps(v_dict))


@login_required
def container_metrics(request, container, **kwargs):
    metrics = [kwargs['model'](container=container)]
    return stats_render(request, metrics, **kwargs)



@login_required