from datetime import datetime

from django.core.management.base import BaseCommand

from couchdbkit import ResourceConflict

from mygpo.core import models
from mygpo.api.models import Podcast
from mygpo.utils import progress
from mygpo.decorators import repeat_on_conflict


class Command(BaseCommand):

    def handle(self, *args, **options):

        started = datetime.now()
        entries = models.Podcast.view('core/podcasts_by_oldid').iterator()
        total = models.Podcast.view('core/podcasts_by_oldid', limit=1).total_rows

        for n, entry in enumerate(entries):
            self.update(entry=entry, started=started)
            progress(n, total)


    @repeat_on_conflict(['entry'])
    def update(self, entry, started):
        try:
            p = Podcast.objects.get(id=entry.oldid)
        except Podcast.DoesNotExist:
            return

        data = models.SubscriberData(
            timestamp        = started,
            subscriber_count = max(0, p.subscriber_count()),
            )
        entry.subscribers.append(data)
        entry.save()

@@ -137,37 +137,8 @@
 core
- import models%0Afrom mygpo.api
 .mod
@@ -155,16 +155,32 @@
  Podcast
+, SubscriberData
 %0Afrom my
@@ -204,16 +204,36 @@
 progress
+, multi_request_view
 %0Afrom my
@@ -397,35 +397,43 @@
 ries = m
-odels.
+ulti_request_view(
 Podcast
-.view(
+, 
 'core/po
@@ -453,19 +453,8 @@
 id')
-.iterator()
 %0A   
@@ -466,23 +466,16 @@
 total = 
-models.
 Podcast.
@@ -515,9 +515,9 @@
 mit=
-1
+0
 ).to
@@ -742,144 +742,15 @@
     
-try:%0A            p = Podcast.objects.get(id=entry.oldid)%0A        except Podcast.DoesNotExist:%0A            return%0A%0A        data = models.
+data = 
 Subs
@@ -839,17 +839,21 @@
  max(0, 
-p
+entry
 .subscri

update update-toplist for CouchDB-based subscriptions