from django.core.management.base import BaseCommand
from mygpo.api.models import Podcast, PodcastGroup, ToplistEntry, Subscription
from django.db.models import Count

class Command(BaseCommand):

    def handle(self, *args, **options):
        old_podcasts = {}
        old_groups = {}
        n=1
        for t in ToplistEntry.objects.all().only('subscriptions', 'podcast', 'podcast_group').order_by('-subscriptions'):
            if t.podcast:
                old_podcasts[t.podcast.id] = n
            else:
                old_groups[t.podcast_group.id] = n
            n += 1

        ToplistEntry.objects.all().delete()

        for p in Podcast.objects.filter(group=None):
            subscriptions = Subscription.objects.filter(podcast=p).values('user').distinct().count()
            ToplistEntry.objects.create(podcast=p, oldplace=old_podcasts.get(p.id, 0), subscriptions=subscriptions)

        for g in PodcastGroup.objects.all():
            subscriptions = Subscription.objects.filter(podcast__in=g.podcasts()).values('user').distinct().count()
            ToplistEntry.objects.create(podcast_group=g, oldplace=old_groups.get(g.id, 0), subscriptions=subscriptions)


@@ -45,16 +45,49 @@
 Command%0A
+from optparse import make_option%0A
 from myg
@@ -222,16 +222,249 @@
 mand):%0A%0A
+    option_list = BaseCommand.option_list + (%0A        make_option('--preserve-oldplace', action='store_true', dest='preserve_oldplace', default=False, help=%22Indicates that the Last (week's) position should not be updated.%22),%0A    )%0A%0A%0A
     def 
@@ -679,16 +679,152 @@
 ions'):%0A
+%0A            if options.get('preserve_oldplace'):%0A                oldplace = t.oldplace%0A            else:%0A                oldplace = n%0A%0A
         
@@ -882,25 +882,32 @@
 dcast.id%5D = 
-n
+oldplace
 %0A           
@@ -962,17 +962,24 @@
 p.id%5D = 
-n
+oldplace
 %0A       

add option --preserve-oldplace to update-toplist