from datetime import datetime, timedelta
from collections import namedtuple

from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import pytz

from games.models import Game, Release


Metric = namedtuple('Metric', 'users, games, releases, downloads, plays')


def growth_rate(current, previous):
    return (current - previous) / float(previous or 1) * 100


def breakdown(weeks):
    print "Date       Users    GR% Games    GR% Releases   GR%"
    report = "{} {:5} {:5.0f}% {:5} {:5.0f}% {:7} {:5.0f}%"
    previous = None
    for week, m in weeks:
        if previous is None:
            print report.format(week.date(), m.users, 0, m.games, 0,
                                m.releases, 0)
        else:
            user_rate = growth_rate(m.users, previous.users)
            game_rate = growth_rate(m.games, previous.games)
            rele_rate = growth_rate(m.releases, previous.releases)
            print report.format(week.date(), m.users, user_rate,
                                m.games, game_rate, m.releases, rele_rate)
        previous = m


def crunch_numbers(begin, end):
    gc = Game.objects.filter(created__lt=end, created__gte=begin).count()
    rc = Release.objects.filter(created__lt=end, created__gte=begin).count()
    uc = User.objects.filter(date_joined__lt=end,
                             date_joined__gte=begin).count()
    # TODO: Add download numbers

    # Add play numbers

    return Metric(uc, gc, rc, 0, 0)


class Command(BaseCommand):
    help = 'Show week-over-week growth rates'

    def handle(self, *args, **options):
        pacific = pytz.timezone('US/Pacific')
        week_begin = pacific.localize(datetime(2013, 12, 13))
        week_end = week_begin + timedelta(days=3)

        print "Week over week"
        print

        weeks = []

        while week_begin < datetime.now(pacific):
            weeks.append((week_begin, crunch_numbers(week_begin, week_end)))
            week_begin = week_end
            week_end = week_begin + timedelta(days=7)

        breakdown(weeks)

        print
        print "Month over month"
        print

        december = pacific.localize(datetime(2013, 12, 13))
        january = pacific.localize(datetime(2014, 1, 1))
        february = pacific.localize(datetime(2014, 2, 1))

        months = [
            (december, crunch_numbers(december, january)),
            (january, crunch_numbers(january, february)),
        ]

        breakdown(months)



@@ -1,12 +1,24 @@
+import json%0A
 from datetim
@@ -178,16 +178,65 @@
 rt User%0A
+from django.conf import settings%0Aimport requests%0A
 import p
@@ -540,16 +540,29 @@
 es   GR%25
+ Plays    GR%25
 %22%0A    re
@@ -604,16 +604,30 @@
 f%7D%25 %7B:7%7D
+ %7B:5.0f%7D%25 %7B:5%7D
  %7B:5.0f%7D
@@ -816,16 +816,28 @@
 eleases,
+ 0, m.plays,
  0)%0A    
@@ -907,16 +907,77 @@
 .users)%0A
+            play_rate = growth_rate(m.plays, previous.plays)%0A
         
@@ -1234,16 +1234,68 @@
 ele_rate
+,%0A                                m.plays, play_rate
 )%0A      
@@ -1657,24 +1657,475 @@
 play numbers
+%0A    keen = %22https://api.keen.io/3.0/projects/%7B%7D/queries/count%22%0A%0A    timeframe = %7B%0A        %22start%22: begin.astimezone(pytz.UTC).isoformat(),%0A        %22end%22: end.astimezone(pytz.UTC).isoformat(),%0A    %7D%0A%0A    params = %7B%0A        %22api_key%22: settings.KEEN_READ_KEY,%0A        %22timeframe%22: json.dumps(timeframe),%0A        %22event_collection%22: %22opens%22,%0A    %7D%0A%0A    resp = requests.get(keen.format(settings.KEEN_PROJECT_ID), params=params)%0A    resp.raise_for_status()
 %0A%0A    return
@@ -2147,17 +2147,44 @@
  rc, 0, 
-0
+resp.json().get('result', 0)
 )%0A%0A%0Aclas

Add support for looking at play data