# Path: bundestagger/bundestag/models.py
# class Parliament(models.Model):
#     number = models.IntegerField()
#     start = models.DateField(default=datetime.datetime.today, null=True, blank=True)
#     end = models.DateField(default=datetime.datetime.today, null=True, blank=True)
#     
#     def __unicode__(self):
#         return u"Parliament %d" % (self.number,)
# 
# class ParliamentSession(models.Model):
#     parliament = models.ForeignKey(Parliament)
#     number = models.PositiveSmallIntegerField(db_index=True)
#     date = models.DateTimeField()
#     until = models.DateTimeField()
#     checked = models.BooleanField(default=False)
#     
#     tags = models.TextField(blank=True)
#     
#     objects = ParliamentSessionManager()
#     
#     def __unicode__(self):
#         return u"%d. Sitzung  (%s) des %d. Deutschen Bundestags" % (self.number, self.date.strftime("%d.%m.%Y"), self.parliament.number)
#         
#     def get_absolute_url(self):
#         return reverse("bundestagger-bundestag-show_session", args=(self.parliament.number, self.number))
#         
#     @property
#     def tag_list(self):
#         return [tag.strip() for tag in self.tags.split(",") if len(tag.strip())>0]
#         
#     def update_tags(self,new_tags):
#         tag_set = set([t.strip() for t in self.tags.split(",") if len(t.strip())>0])
#         tag_set.update([t.strip() for t in new_tags.split(",") if len(t.strip())>0])
#         self.tags = ",".join(tag_set)
#         self.clear_cache()
#         self.save()
#     
#     @property
#     def document_url(self):
#         return "http://dip21.bundestag.de/dip21/btp/%(leg)d/%(leg)d%(id)s.pdf" % {"leg":self.parliament.number, "id": padd_zeros(self.number)}
#     
#     def clear_cache(self):
#         invalidate_cache(reverse("bundestagger-bundestag-list_sessions"))
#         last_speech = self.speech_set.order_by("-ordernr")[0]
#         url = last_speech.get_base_url()
#         invalidate_cache_all_pages(url, last_speech.ordernr, settings.SPEECHES_PER_PAGE)
# 
# class Speech(models.Model):
#     session = models.ForeignKey(ParliamentSession)
#     ordernr = models.IntegerField()
#     speaker = models.ForeignKey(Politician)
#     start = models.DateTimeField(blank=True, default=None, null=True)
#     end = models.DateTimeField(blank=True, default=None, null=True)
#     webtv = models.IntegerField(blank=True, null=True)
#     
#     tags = TagField(blank=True)
#     
#     def save(self, *args, **kwargs):
#         super(Speech,self).save(*args, **kwargs)
#         self.session.update_tags(self.tags)
#         
#     
#     def __unicode__(self):
#         return u"Rede von %s in der %s" % (self.speaker, self.session)
#         
#     def text(self):
#         return u"\n".join(map(lambda x:x.text, self.speechpart_set.order_by("ordernr")))
#         
#     @property
#     def tag_list(self):
#         return [tag.strip() for tag in self.tags.split(",") if len(tag.strip())>0]
#     
#     @property
#     def webtv_url(self):
#         if self.webtv is not None:
#             return u"http://webtv.bundestag.de/iptv/player/macros/_v_f_514_de/od_player.html?singleton=true&content=%d" % (self.webtv,)
#         return u""
#     
#     @property
#     def webtv_search(self):
#         url = u"http://webtv.bundestag.de/iptv/player/macros/bttv/list.html?pageOffset=0&pageLength=40&sort=2&lastName=%(lastname)s&firstName=%(firstname)s&fraction=&meetingNumber=%(session)s&period=%(period)s&startDay=&endDay=&topic=&submit=Suchen"
#         return url % {  "firstname": self.speaker.first_name, 
#                         "lastname": self.speaker.last_name,
#                         "session": self.session.number,
#                         "period": self.session.parliament.number
#                         }
#     
#     def get_base_url(self):
#         return reverse("bundestagger-bundestag-show_session", args=(self.session.parliament.number, self.session.number))
#         
#     def get_absolute_url(self):
#         page = get_page(self.ordernr, settings.SPEECHES_PER_PAGE)
#         if page == 1:
#             page = ""
#         else:
#             page = "?page=%d" % page
#         fragment = "#speech-%d" % self.id
#         return self.get_base_url() + page + fragment
# 
#     def clear_cache(self):
#         url = self.get_base_url()
#         invalidate_cache(url, self.ordernr, settings.SPEECHES_PER_PAGE)


from django.core.urlresolvers import reverse
from django.http import Http404
from django.conf import settings
from piston.handler import BaseHandler
from piston.decorator import decorator
from tagging.models import Tag, TaggedItem
from bundestagger.bundestag.models import Parliament, ParliamentSession, Speech
                from random import randint




THROTTLE_PARAMS = [10, 60, 'user_reads']

def throttle(*args, **kwargs):
    @decorator
    def inner_func(func, *inner_args, **inner_kwargs):
        return func(*inner_args, **inner_kwargs)
    return inner_func

def fullurl(url):
    return settings.SITE_DOMAIN + url

class ParliamentHandler(BaseHandler):
    allowed_methods = ('GET',)

    @throttle(*THROTTLE_PARAMS)   
    def read(self, request, parliament_number=None):
        if parliament_number is None:
            return [{"href": self.get_url(p)} for p in Parliament.objects.all()]
        else:
            try:

# Path: bundestagger/bundestag/models.py
# class Parliament(models.Model):
#     number = models.IntegerField()
#     start = models.DateField(default=datetime.datetime.today, null=True, blank=True)
#     end = models.DateField(default=datetime.datetime.today, null=True, blank=True)
#     
#     def __unicode__(self):
#         return u"Parliament %d" % (self.number,)
# 
# class ParliamentSession(models.Model):
#     parliament = models.ForeignKey(Parliament)
#     number = models.PositiveSmallIntegerField(db_index=True)
#     date = models.DateTimeField()
#     until = models.DateTimeField()
#     checked = models.BooleanField(default=False)
#     
#     tags = models.TextField(blank=True)
#     
#     objects = ParliamentSessionManager()
#     
#     def __unicode__(self):
#         return u"%d. Sitzung  (%s) des %d. Deutschen Bundestags" % (self.number, self.date.strftime("%d.%m.%Y"), self.parliament.number)
#         
#     def get_absolute_url(self):
#         return reverse("bundestagger-bundestag-show_session", args=(self.parliament.number, self.number))
#         
#     @property
#     def tag_list(self):
#         return [tag.strip() for tag in self.tags.split(",") if len(tag.strip())>0]
#         
#     def update_tags(self,new_tags):
#         tag_set = set([t.strip() for t in self.tags.split(",") if len(t.strip())>0])
#         tag_set.update([t.strip() for t in new_tags.split(",") if len(t.strip())>0])
#         self.tags = ",".join(tag_set)
#         self.clear_cache()
#         self.save()
#     
#     @property
#     def document_url(self):
#         return "http://dip21.bundestag.de/dip21/btp/%(leg)d/%(leg)d%(id)s.pdf" % {"leg":self.parliament.number, "id": padd_zeros(self.number)}
#     
#     def clear_cache(self):
#         invalidate_cache(reverse("bundestagger-bundestag-list_sessions"))
#         last_speech = self.speech_set.order_by("-ordernr")[0]
#         url = last_speech.get_base_url()
#         invalidate_cache_all_pages(url, last_speech.ordernr, settings.SPEECHES_PER_PAGE)
# 
# class Speech(models.Model):
#     session = models.ForeignKey(ParliamentSession)
#     ordernr = models.IntegerField()
#     speaker = models.ForeignKey(Politician)
#     start = models.DateTimeField(blank=True, default=None, null=True)
#     end = models.DateTimeField(blank=True, default=None, null=True)
#     webtv = models.IntegerField(blank=True, null=True)
#     
#     tags = TagField(blank=True)
#     
#     def save(self, *args, **kwargs):
#         super(Speech,self).save(*args, **kwargs)
#         self.session.update_tags(self.tags)
#         
#     
#     def __unicode__(self):
#         return u"Rede von %s in der %s" % (self.speaker, self.session)
#         
#     def text(self):
#         return u"\n".join(map(lambda x:x.text, self.speechpart_set.order_by("ordernr")))
#         
#     @property
#     def tag_list(self):
#         return [tag.strip() for tag in self.tags.split(",") if len(tag.strip())>0]
#     
#     @property
#     def webtv_url(self):
#         if self.webtv is not None:
#             return u"http://webtv.bundestag.de/iptv/player/macros/_v_f_514_de/od_player.html?singleton=true&content=%d" % (self.webtv,)
#         return u""
#     
#     @property
#     def webtv_search(self):
#         url = u"http://webtv.bundestag.de/iptv/player/macros/bttv/list.html?pageOffset=0&pageLength=40&sort=2&lastName=%(lastname)s&firstName=%(firstname)s&fraction=&meetingNumber=%(session)s&period=%(period)s&startDay=&endDay=&topic=&submit=Suchen"
#         return url % {  "firstname": self.speaker.first_name, 
#                         "lastname": self.speaker.last_name,
#                         "session": self.session.number,
#                         "period": self.session.parliament.number
#                         }
#     
#     def get_base_url(self):
#         return reverse("bundestagger-bundestag-show_session", args=(self.session.parliament.number, self.session.number))
#         
#     def get_absolute_url(self):
#         page = get_page(self.ordernr, settings.SPEECHES_PER_PAGE)
#         if page == 1:
#             page = ""
#         else:
#             page = "?page=%d" % page
#         fragment = "#speech-%d" % self.id
#         return self.get_base_url() + page + fragment
# 
#     def clear_cache(self):
#         url = self.get_base_url()
#         invalidate_cache(url, self.ordernr, settings.SPEECHES_PER_PAGE)


# Path: bundestagger/api/handlers.py
from django.core.urlresolvers import reverse
from django.http import Http404
from django.conf import settings
from piston.handler import BaseHandler
from piston.decorator import decorator
from tagging.models import Tag, TaggedItem
from bundestagger.bundestag.models import Parliament, ParliamentSession, Speech
                from random import randint





THROTTLE_PARAMS = [10, 60, 'user_reads']

def throttle(*args, **kwargs):
    @decorator
    def inner_func(func, *inner_args, **inner_kwargs):
        return func(*inner_args, **inner_kwargs)
    return inner_func

def fullurl(url):
    return settings.SITE_DOMAIN + url

class ParliamentHandler(BaseHandler):
    allowed_methods = ('GET',)

    @throttle(*THROTTLE_PARAMS)   
    def read(self, request, parliament_number=None):
        if parliament_number is None:
            return [{"href": self.get_url(p)} for p in Parliament.objects.all()]
        else:
            try:

                p = Parliament.objects.get(number=int(parliament_number))