from django.core.management.base import BaseCommand, CommandError
from django.db.models import F, Q
from django.utils import timezone
import json
import pydoc
import requests
from cityhallmonitor.models import Matter, MatterAttachment

_legistar_matter_attachments_url = \
    'http://webapi.legistar.com/v1/chicago/Matters/%(matter_id)s/Attachments'
API_DATA_TYPE = 'MatterAttachments'


class Command(BaseCommand):
    help = 'Get attachments for updated matters from the chicago legistar API.'

    def add_arguments(self, parser):
        parser.add_argument('matter_id', nargs='?', help='Matter ID')

    def fetch(self, matter):
        url = _legistar_matter_attachments_url % { 'matter_id': matter.id }
        self.stdout.write('Downloading %s...' % url)   
        headers = {'Accept': 'text/json'}
        r = requests.get(url, headers=headers)
        if not r.ok:
            raise Exception('Error downloading %s [%d]' \
                % (url, r.status_code))
        for i, item in enumerate(r.json()):
            try:
                r = MatterAttachment.from_json(matter.id, item)
                r.save()
            except TypeError as e:
                print(item)
                raise e
        matter.attachments_obtained_at = timezone.now()
        matter.save()

    def handle(self, *args, **options):
        matter_id = options['matter_id']
        if matter_id:
            self.stdout.write(
                'Fetching attachments for matter ID %s.' % matter_id)
            matter = Matter.objects.get(id=matter_id)
            self.fetch(matter)
        else:
            self.stdout.write('Fetching all updated matter attachments.')
            for matter in Matter.objects.filter(
                    Q(attachments_obtained_at=None)
                    | Q(attachments_obtained_at__lte=F('last_modified')) ):
                self.fetch(matter)
        self.stdout.write('Done')
        

@@ -1324,16 +1324,33 @@
 tions):%0A
+        try:%0A    
         
@@ -1390,16 +1390,20 @@
         
+    
 if matte
@@ -1412,32 +1412,36 @@
 id:%0A            
+  
+  
 self.stdout.writ
@@ -1443,16 +1443,20 @@
 .write(%0A
+    
         
@@ -1464,16 +1464,19 @@
        '
+%25s 
 Fetching
@@ -1507,17 +1507,56 @@
 ID %25s.' 
-%25
+%5C%0A                    %25 (timezone.now(),
  matter_
@@ -1550,33 +1550,38 @@
 ow(), matter_id)
-%0A
+)%0A    
             matt
@@ -1622,32 +1622,36 @@
 id)%0A            
+   
+ 
 self.fetch(matte
@@ -1661,16 +1661,20 @@
         
+    
 else:%0A  
@@ -1675,32 +1675,36 @@
 se:%0A            
+ 
+   
 self.stdout.writ
@@ -1705,17 +1705,41 @@
 t.write(
-'
+%0A                    '%25s 
 Fetching
@@ -1771,18 +1771,61 @@
 hments.'
-)%0A
+ %5C%0A                    %25 timezone.now())%0A    
         
@@ -1885,16 +1885,20 @@
         
+   
+ 
 Q(attach
@@ -1921,16 +1921,20 @@
 t=None)%0A
+    
         
@@ -2009,32 +2009,36 @@
                 
+    
 self.fetch(matte
@@ -2040,32 +2040,36 @@
 matter)%0A        
+  
+  
 self.stdout.writ
@@ -2075,15 +2075,203 @@
 te('
+%25s 
 Done'
-)%0A
+ %25 timezone.now())%0A        except Exception as e:%0A            self.stdout.write('ERROR: %25s %25s' %25 (type(e), str(e)))%0A            self.stdout.write('%25s Ending'  %25 timezone.now())%0A          
     

Add timestamps and exception handling to pull_attachments cmd