# Path: core/helpers.py
# def get_date_truncate(truncate, fieldname, timezone):
#     if connection.vendor != 'postgresql':
#         warnings.warn('Not running on PostgreSQL, timezone support not entirely functional on other backends yet. '
#                       'Falling back to no-timezone mode in some calculations.')
#         return connection.ops.date_trunc_sql(truncate, fieldname)
#     return "DATE_TRUNC('{0}', {1} AT TIME ZONE INTERVAL '{2}')".format(truncate, fieldname, timezone_offset(timezone))
# 
# Path: core/models.py
# class Website(models.Model):
#     user = models.ForeignKey(settings.AUTH_USER_MODEL)
#     name = models.CharField(max_length=255)
#     url = models.URLField()
#     timezone = TimeZoneField()
# 
#     def __unicode__(self):
#         return self.name
# 
#     def view_count_today(self):
#         today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
#         return len(PageView.objects.filter(session__website=self,
#                                            view_timestamp__gt=today_midnight))
# 
# class PageView(models.Model):
#     session = models.ForeignKey('Session')
#     path = models.CharField(max_length=255)
#     view_timestamp = models.DateTimeField(auto_now_add=True)
#     # Duration in seconds
#     duration = models.IntegerField(default=0)
#     active_duration = models.IntegerField(default=0)
# 
#     class Meta:
#         ordering = ('view_timestamp', )
# 
# class Session(models.Model):
#     timestamp = models.DateTimeField(auto_now_add=True)
#     user = models.ForeignKey('TrackerUser')
#     website = models.ForeignKey('Website')
# 
#     class Meta:
#         ordering = ('timestamp', )
# 
# Path: overview/helpers.py
# def daterange(start_date, end_date):
#     for n in range(int((end_date - start_date).days)):
#         yield start_date + timedelta(days=n)


import datetime
import json
from core.helpers import get_date_truncate
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.forms import model_to_dict
from django.http import Http404
from django.utils import timezone
from django.utils.datastructures import SortedDict
from django.utils.decorators import method_decorator
from django.utils.safestring import mark_safe
from core.models import Website, PageView, Session
from overview.helpers import daterange
        try:
            website = Website.objects.get(pk=self.kwargs['website_id'])
        except Website.DoesNotExist:
            raise Http404('No such website.')
        if website.user != self.request.user:
            raise PermissionDenied('You don\'t have permission to view this website.')
        return website

    def website_to_json(self, website):
        return mark_safe(json.dumps(model_to_dict(website, exclude=('timezone', ))))


class ChartsUtilityMixin(object):
    num_days = None

    @property
    def pageviews(self):
        return PageView.objects.filter(session__website=self.kwargs['website_id'])

    @property
    def pageviews_today(self):
        return self.pageviews.filter(view_timestamp__gt=self.today_midnight())

    @property
    def pageviews_yesterday(self):
        return self.pageviews.filter(view_timestamp__lte=self.today_midnight(),
                                     view_timestamp__gte=self.today_midnight() - timezone.timedelta(days=1))

    @property
    def sessions(self):

# Path: core/helpers.py
# def get_date_truncate(truncate, fieldname, timezone):
#     if connection.vendor != 'postgresql':
#         warnings.warn('Not running on PostgreSQL, timezone support not entirely functional on other backends yet. '
#                       'Falling back to no-timezone mode in some calculations.')
#         return connection.ops.date_trunc_sql(truncate, fieldname)
#     return "DATE_TRUNC('{0}', {1} AT TIME ZONE INTERVAL '{2}')".format(truncate, fieldname, timezone_offset(timezone))
# 
# Path: core/models.py
# class Website(models.Model):
#     user = models.ForeignKey(settings.AUTH_USER_MODEL)
#     name = models.CharField(max_length=255)
#     url = models.URLField()
#     timezone = TimeZoneField()
# 
#     def __unicode__(self):
#         return self.name
# 
#     def view_count_today(self):
#         today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
#         return len(PageView.objects.filter(session__website=self,
#                                            view_timestamp__gt=today_midnight))
# 
# class PageView(models.Model):
#     session = models.ForeignKey('Session')
#     path = models.CharField(max_length=255)
#     view_timestamp = models.DateTimeField(auto_now_add=True)
#     # Duration in seconds
#     duration = models.IntegerField(default=0)
#     active_duration = models.IntegerField(default=0)
# 
#     class Meta:
#         ordering = ('view_timestamp', )
# 
# class Session(models.Model):
#     timestamp = models.DateTimeField(auto_now_add=True)
#     user = models.ForeignKey('TrackerUser')
#     website = models.ForeignKey('Website')
# 
#     class Meta:
#         ordering = ('timestamp', )
# 
# Path: overview/helpers.py
# def daterange(start_date, end_date):
#     for n in range(int((end_date - start_date).days)):
#         yield start_date + timedelta(days=n)


# Path: core/mixins.py
import datetime
import json
from core.helpers import get_date_truncate
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.forms import model_to_dict
from django.http import Http404
from django.utils import timezone
from django.utils.datastructures import SortedDict
from django.utils.decorators import method_decorator
from django.utils.safestring import mark_safe
from core.models import Website, PageView, Session
from overview.helpers import daterange

        try:
            website = Website.objects.get(pk=self.kwargs['website_id'])
        except Website.DoesNotExist:
            raise Http404('No such website.')
        if website.user != self.request.user:
            raise PermissionDenied('You don\'t have permission to view this website.')
        return website

    def website_to_json(self, website):
        return mark_safe(json.dumps(model_to_dict(website, exclude=('timezone', ))))


class ChartsUtilityMixin(object):
    num_days = None

    @property
    def pageviews(self):
        return PageView.objects.filter(session__website=self.kwargs['website_id'])

    @property
    def pageviews_today(self):
        return self.pageviews.filter(view_timestamp__gt=self.today_midnight())

    @property
    def pageviews_yesterday(self):
        return self.pageviews.filter(view_timestamp__lte=self.today_midnight(),
                                     view_timestamp__gte=self.today_midnight() - timezone.timedelta(days=1))

    @property
    def sessions(self):

        return Session.objects.filter(website=self.kwargs['website_id'])