# Path: mailit/models.py
# class MailItTemplate(models.Model):
#     subject_template = models.CharField(
#         max_length=255,
#         default="{subject}",
#         help_text=_('You can use {subject}, {content}, {person}, {author}, {site_url}, {site_name}, and {owner_email}'),
#         )
#     content_template = models.TextField(
#         help_text=_('You can use {subject}, {content}, {person}, {author}, {site_url}, {site_name}, and {owner_email}'),
#         blank=True,
#         )
#     content_html_template = models.TextField(
#         blank=True,
#         help_text=_('You can use {subject}, {content}, {person}, {author}, {site_url}, {site_name}, and {owner_email}'),
#         )
#     writeitinstance = models.OneToOneField(WriteItInstance, related_name='mailit_template')
# 
#     def get_content_template(self):
#         return self.content_template or default_content_template
# 
# Path: instance/models.py
# class WriteItInstance(models.Model):
#     """WriteItInstance: Entity that groups messages and people
#     for usability purposes. E.g. 'Candidates running for president'"""
#     name = models.CharField(max_length=255)
#     description = models.CharField(max_length=512, blank=True)
#     slug = AutoSlugField(populate_from='name', unique=True)
#     persons = models.ManyToManyField(Person,
#         related_name='writeit_instances',
#         through='Membership')
#     owner = models.ForeignKey(User, related_name="writeitinstances")
# 
#     def add_person(self, person):
#         Membership.objects.get_or_create(writeitinstance=self, person=person)
# 
#     @property
#     def persons_with_contacts(self):
#         return self.persons.filter(contact__writeitinstance=self, contact__isnull=False).distinct()
# 
#     def relate_with_persons_from_popit_api_instance(self, popit_api_instance):
#         try:
#             popit_api_instance.fetch_all_from_api(writeitinstance=self)
#         except ConnectionError, e:
#             self.do_something_with_a_vanished_popit_api_instance(popit_api_instance)
#             e.message = _('We could not connect with the URL')
#             return (False, e)
#         except Exception, e:
#             self.do_something_with_a_vanished_popit_api_instance(popit_api_instance)
#             return (False, e)
#         persons = Person.objects.filter(api_instance=popit_api_instance)
#         for person in persons:
#             # There could be several memberships created.
#             memberships = Membership.objects.filter(writeitinstance=self, person=person)
#             if memberships.count() == 0:
#                 Membership.objects.create(writeitinstance=self, person=person)
#             if memberships.count() > 1:
#                 membership = memberships[0]
#                 memberships.exclude(id=membership.id).delete()
# 
#         return (True, None)
# 
#     def do_something_with_a_vanished_popit_api_instance(self, popit_api_instance):
#         pass
# 
#     def _load_persons_from_a_popit_api(self, popit_api_instance):
#         success_relating_people, error = self.relate_with_persons_from_popit_api_instance(popit_api_instance)
#         record = WriteitInstancePopitInstanceRecord.objects.get(
#             writeitinstance=self,
#             popitapiinstance=popit_api_instance
#             )
#         if success_relating_people:
#             record.set_status('success')
#         else:
#             if isinstance(error, ConnectionError):
#                 record.set_status('error', _('We could not connect with the URL'))
#             else:
#                 record.set_status('error', error.message)
#         return (success_relating_people, error)
# 
#     def load_persons_from_a_popit_api(self, popit_url):
#         '''This is an async wrapper for getting people from the api'''
#         popit_api_instance, created = PopitApiInstance.objects.get_or_create(url=popit_url)
#         record, created = WriteitInstancePopitInstanceRecord.objects.get_or_create(
#             writeitinstance=self,
#             popitapiinstance=popit_api_instance
#             )
#         if not created:
#             record.updated = datetime.datetime.today()
#             record.save()
#         record.set_status('inprogress')
#         from nuntium.tasks import pull_from_popit
#         return pull_from_popit.delay(self, popit_api_instance)
# 
#     def get_absolute_url(self):
#         return reverse('instance_detail', subdomain=self.slug)
# 
#     @property
#     def pulling_from_popit_status(self):
#         records = WriteitInstancePopitInstanceRecord.objects.filter(writeitinstance=self)
#         result = {'nothing': 0, 'inprogress': 0, 'success': 0, 'error': 0}
#         for record in records:
#             result[record.status] += 1
#         return result
# 
#     @property
#     def can_create_messages(self):
#         if self.config.allow_messages_using_form and \
#                 self.contacts.exists():
#             return True
# 
#         return False
# 
#     def __unicode__(self):
#         return self.name


from django.views.generic.edit import UpdateView
from .models import MailItTemplate
from .forms import MailitTemplateForm
from subdomains.utils import reverse
from django.shortcuts import get_object_or_404
from django.http import Http404
from instance.models import WriteItInstance
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator


class MailitTemplateUpdateView(UpdateView):
    model = MailItTemplate
    form_class = MailitTemplateForm

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(MailitTemplateUpdateView, self).dispatch(*args, **kwargs)

    def get_object(self):
        self.writeitinstance = get_object_or_404(WriteItInstance, slug=self.request.subdomain)
        if not self.writeitinstance.owner.__eq__(self.request.user):
            raise Http404
        self.object = self.writeitinstance.mailit_template
        return self.object

    def get_form_kwargs(self):

# Path: mailit/models.py
# class MailItTemplate(models.Model):
#     subject_template = models.CharField(
#         max_length=255,
#         default="{subject}",
#         help_text=_('You can use {subject}, {content}, {person}, {author}, {site_url}, {site_name}, and {owner_email}'),
#         )
#     content_template = models.TextField(
#         help_text=_('You can use {subject}, {content}, {person}, {author}, {site_url}, {site_name}, and {owner_email}'),
#         blank=True,
#         )
#     content_html_template = models.TextField(
#         blank=True,
#         help_text=_('You can use {subject}, {content}, {person}, {author}, {site_url}, {site_name}, and {owner_email}'),
#         )
#     writeitinstance = models.OneToOneField(WriteItInstance, related_name='mailit_template')
# 
#     def get_content_template(self):
#         return self.content_template or default_content_template
# 
# Path: instance/models.py
# class WriteItInstance(models.Model):
#     """WriteItInstance: Entity that groups messages and people
#     for usability purposes. E.g. 'Candidates running for president'"""
#     name = models.CharField(max_length=255)
#     description = models.CharField(max_length=512, blank=True)
#     slug = AutoSlugField(populate_from='name', unique=True)
#     persons = models.ManyToManyField(Person,
#         related_name='writeit_instances',
#         through='Membership')
#     owner = models.ForeignKey(User, related_name="writeitinstances")
# 
#     def add_person(self, person):
#         Membership.objects.get_or_create(writeitinstance=self, person=person)
# 
#     @property
#     def persons_with_contacts(self):
#         return self.persons.filter(contact__writeitinstance=self, contact__isnull=False).distinct()
# 
#     def relate_with_persons_from_popit_api_instance(self, popit_api_instance):
#         try:
#             popit_api_instance.fetch_all_from_api(writeitinstance=self)
#         except ConnectionError, e:
#             self.do_something_with_a_vanished_popit_api_instance(popit_api_instance)
#             e.message = _('We could not connect with the URL')
#             return (False, e)
#         except Exception, e:
#             self.do_something_with_a_vanished_popit_api_instance(popit_api_instance)
#             return (False, e)
#         persons = Person.objects.filter(api_instance=popit_api_instance)
#         for person in persons:
#             # There could be several memberships created.
#             memberships = Membership.objects.filter(writeitinstance=self, person=person)
#             if memberships.count() == 0:
#                 Membership.objects.create(writeitinstance=self, person=person)
#             if memberships.count() > 1:
#                 membership = memberships[0]
#                 memberships.exclude(id=membership.id).delete()
# 
#         return (True, None)
# 
#     def do_something_with_a_vanished_popit_api_instance(self, popit_api_instance):
#         pass
# 
#     def _load_persons_from_a_popit_api(self, popit_api_instance):
#         success_relating_people, error = self.relate_with_persons_from_popit_api_instance(popit_api_instance)
#         record = WriteitInstancePopitInstanceRecord.objects.get(
#             writeitinstance=self,
#             popitapiinstance=popit_api_instance
#             )
#         if success_relating_people:
#             record.set_status('success')
#         else:
#             if isinstance(error, ConnectionError):
#                 record.set_status('error', _('We could not connect with the URL'))
#             else:
#                 record.set_status('error', error.message)
#         return (success_relating_people, error)
# 
#     def load_persons_from_a_popit_api(self, popit_url):
#         '''This is an async wrapper for getting people from the api'''
#         popit_api_instance, created = PopitApiInstance.objects.get_or_create(url=popit_url)
#         record, created = WriteitInstancePopitInstanceRecord.objects.get_or_create(
#             writeitinstance=self,
#             popitapiinstance=popit_api_instance
#             )
#         if not created:
#             record.updated = datetime.datetime.today()
#             record.save()
#         record.set_status('inprogress')
#         from nuntium.tasks import pull_from_popit
#         return pull_from_popit.delay(self, popit_api_instance)
# 
#     def get_absolute_url(self):
#         return reverse('instance_detail', subdomain=self.slug)
# 
#     @property
#     def pulling_from_popit_status(self):
#         records = WriteitInstancePopitInstanceRecord.objects.filter(writeitinstance=self)
#         result = {'nothing': 0, 'inprogress': 0, 'success': 0, 'error': 0}
#         for record in records:
#             result[record.status] += 1
#         return result
# 
#     @property
#     def can_create_messages(self):
#         if self.config.allow_messages_using_form and \
#                 self.contacts.exists():
#             return True
# 
#         return False
# 
#     def __unicode__(self):
#         return self.name


# Path: mailit/views.py
from django.views.generic.edit import UpdateView
from .models import MailItTemplate
from .forms import MailitTemplateForm
from subdomains.utils import reverse
from django.shortcuts import get_object_or_404
from django.http import Http404
from instance.models import WriteItInstance
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator



class MailitTemplateUpdateView(UpdateView):
    model = MailItTemplate
    form_class = MailitTemplateForm

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(MailitTemplateUpdateView, self).dispatch(*args, **kwargs)

    def get_object(self):
        self.writeitinstance = get_object_or_404(WriteItInstance, slug=self.request.subdomain)
        if not self.writeitinstance.owner.__eq__(self.request.user):
            raise Http404
        self.object = self.writeitinstance.mailit_template
        return self.object

    def get_form_kwargs(self):

        kwargs = super(MailitTemplateUpdateView, self).get_form_kwargs()