# Path: wbc/process/models.py
# class Publication(Model):
#     process_step = models.ForeignKey('ProcessStep', related_name='publications', verbose_name="Verfahrensschritt")
#     description  = models.TextField(blank=True, verbose_name="Beschreibung")
#     place        = models.ForeignKey('Place', related_name='publications', verbose_name="Ort")
#     begin        = models.DateField(verbose_name="Beginn der Auslegungszeit")
#     end          = models.DateField(verbose_name="Ende der Auslegungszeit")
#     office       = models.TextField(blank=True, verbose_name="Auslegungsstelle")
#     office_hours = models.TextField(blank=True, verbose_name="Öffnungszeiten der Auslegungsstelle")
#     department   = models.ForeignKey(Department, verbose_name="Verantwortliche Behörde")
#     link         = models.URLField(blank=True)
# 
#     def get_absolute_url(self):
#         return reverse('place', kwargs={'pk': self.place.pk})
# 
#     def get_update_url(self):
#         return reverse('publication_update', kwargs={'pk': self.pk})
# 
#     def get_delete_url(self):
#         return reverse('publication_delete', kwargs={'pk': self.pk})
# 
#     def __str__(self):
#         return str(self.place) + ', ' + self.process_step.name
# 
#     def __unicode__(self):
#         return unicode(self.__str__())
# 
#     class Meta:
#         ordering            = ("-end",)
#         verbose_name        = u"Veröffentlichung"
#         verbose_name_plural = u"Veröffentlichungen"
# 
# Path: wbc/news/models.py
# class Subscriber(Model):
#     email = models.EmailField(unique=True)
#     entities = models.ManyToManyField(Entity, related_name='subscribers')
# 
#     def __unicode__(self):
#         return self.email
# 
#     class Meta:
#         verbose_name = "Abonnent"
#         verbose_name_plural = "Abonnenten"
# 
# class Newsletter(Model):
#     send = models.DateTimeField(verbose_name="Gesendet")
#     n = models.IntegerField(verbose_name="Anzahl Mails")
# 
#     def __unicode__(self):
#         return self.send.strftime("%d. %m. %Y, %H:%M:%S")
# 
#     class Meta:
#         verbose_name = "Newsletter"
#         verbose_name_plural = "Newsletter"
# 
# Path: wbc/news/lib.py
# def send_mail(to, template, context):
#     if type(to) != list:
#         to = [to,]
# 
#     t = loader.get_template(template)
#     c = Context(context)
# 
#     html_part = t.render(c)
#     text_part = strip_tags(html_part)
# 
#     subject,body = text_part.split('---')
# 
#     msg = EmailMultiAlternatives(subject.strip(),body.strip(),settings.EMAIL_FROM,to)
# 
#     return msg.send()


from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from django.utils.timezone import now
from django.db.models import Max
from wbc.process.models import Publication
from wbc.news.models import Subscriber, Newsletter
from wbc.news.lib import send_mail
from django.utils.translation import activate
            # gather the subscription for the subscribers
            news_items = []
            for entity in subscriber.entities.all():
                for publication in publications:
                    if entity in publication.place.entities.all():
                        news_items.append(publication)

            # Doubletten ausfiltern
            news_items = list(set(news_items))

            # an zu verschickende News anhängen
            news[subscriber.email] = news_items

        # get the path for places the unsubscribe from a reverse url lookup
        place_path = reverse('wbc.process.views.place',args=['0']).rstrip('0/') + '/'
        unsubscribe_path = reverse('wbc.news.views.unsubscribe',args=['0']).rstrip('0/') + '/'

        i = 0
        for email in news:
            # Mail abschicken
            if news[email]:
                i += 1

                send_mail(email, 'news/mail/newsletter.html', {
                    'publications': news[email],
                    'place_link': settings.SITE_URL + place_path,
                    'unsubscribe_link': settings.SITE_URL + unsubscribe_path + email
                })

        # store information about this newsletter in the database

# Path: wbc/process/models.py
# class Publication(Model):
#     process_step = models.ForeignKey('ProcessStep', related_name='publications', verbose_name="Verfahrensschritt")
#     description  = models.TextField(blank=True, verbose_name="Beschreibung")
#     place        = models.ForeignKey('Place', related_name='publications', verbose_name="Ort")
#     begin        = models.DateField(verbose_name="Beginn der Auslegungszeit")
#     end          = models.DateField(verbose_name="Ende der Auslegungszeit")
#     office       = models.TextField(blank=True, verbose_name="Auslegungsstelle")
#     office_hours = models.TextField(blank=True, verbose_name="Öffnungszeiten der Auslegungsstelle")
#     department   = models.ForeignKey(Department, verbose_name="Verantwortliche Behörde")
#     link         = models.URLField(blank=True)
# 
#     def get_absolute_url(self):
#         return reverse('place', kwargs={'pk': self.place.pk})
# 
#     def get_update_url(self):
#         return reverse('publication_update', kwargs={'pk': self.pk})
# 
#     def get_delete_url(self):
#         return reverse('publication_delete', kwargs={'pk': self.pk})
# 
#     def __str__(self):
#         return str(self.place) + ', ' + self.process_step.name
# 
#     def __unicode__(self):
#         return unicode(self.__str__())
# 
#     class Meta:
#         ordering            = ("-end",)
#         verbose_name        = u"Veröffentlichung"
#         verbose_name_plural = u"Veröffentlichungen"
# 
# Path: wbc/news/models.py
# class Subscriber(Model):
#     email = models.EmailField(unique=True)
#     entities = models.ManyToManyField(Entity, related_name='subscribers')
# 
#     def __unicode__(self):
#         return self.email
# 
#     class Meta:
#         verbose_name = "Abonnent"
#         verbose_name_plural = "Abonnenten"
# 
# class Newsletter(Model):
#     send = models.DateTimeField(verbose_name="Gesendet")
#     n = models.IntegerField(verbose_name="Anzahl Mails")
# 
#     def __unicode__(self):
#         return self.send.strftime("%d. %m. %Y, %H:%M:%S")
# 
#     class Meta:
#         verbose_name = "Newsletter"
#         verbose_name_plural = "Newsletter"
# 
# Path: wbc/news/lib.py
# def send_mail(to, template, context):
#     if type(to) != list:
#         to = [to,]
# 
#     t = loader.get_template(template)
#     c = Context(context)
# 
#     html_part = t.render(c)
#     text_part = strip_tags(html_part)
# 
#     subject,body = text_part.split('---')
# 
#     msg = EmailMultiAlternatives(subject.strip(),body.strip(),settings.EMAIL_FROM,to)
# 
#     return msg.send()


# Path: wbc/news/management/commands/daily-news.py
from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from django.utils.timezone import now
from django.db.models import Max
from wbc.process.models import Publication
from wbc.news.models import Subscriber, Newsletter
from wbc.news.lib import send_mail
from django.utils.translation import activate

            # gather the subscription for the subscribers
            news_items = []
            for entity in subscriber.entities.all():
                for publication in publications:
                    if entity in publication.place.entities.all():
                        news_items.append(publication)

            # Doubletten ausfiltern
            news_items = list(set(news_items))

            # an zu verschickende News anhängen
            news[subscriber.email] = news_items

        # get the path for places the unsubscribe from a reverse url lookup
        place_path = reverse('wbc.process.views.place',args=['0']).rstrip('0/') + '/'
        unsubscribe_path = reverse('wbc.news.views.unsubscribe',args=['0']).rstrip('0/') + '/'

        i = 0
        for email in news:
            # Mail abschicken
            if news[email]:
                i += 1

                send_mail(email, 'news/mail/newsletter.html', {
                    'publications': news[email],
                    'place_link': settings.SITE_URL + place_path,
                    'unsubscribe_link': settings.SITE_URL + unsubscribe_path + email
                })

        # store information about this newsletter in the database

        Newsletter(send=now(),n=i).save()