# Path: privagal/gallery/models.py
# class Gallery(AuthTokenPageMixin, Page):
#     date = models.DateField("Post date", default=timezone.now)
#     body = RichTextField(blank=True)
# 
#     content_panels = Page.content_panels + [
#         FieldPanel('date'),
#         FieldPanel('body', classname="full"),
#         InlinePanel('images', label=_('Images')),
#     ]
# 
#     parent_page_types = ['timeline.Timeline']
#     subpage_types = []
# 
#     class Meta:
#         db_table = 'privagal_gallery'
#         verbose_name = _("Gallery")
# 
#     def delete(self, *args, **kwargs):
#         with transaction.atomic():
#             # We need to call model instance method BEFORE deleting the
#             # instance itself to delete image in cascade. This is worst for
#             # performance than using QuerySet manager but it keep it stupid.
#             for image in self.images.all():
#                 image.delete()
#             super(Gallery, self).delete(*args, **kwargs)
# 
#     @property
#     def image_teaser(self):
#         return self.images.first()
# 
#     @property
#     def teaser(self):
#         return loader.render_to_string(
#             'gallery/gallery_teaser.html',
#             {
#                 PAGE_TEMPLATE_VAR: self,
#             },
#         )
# 
#     def serve_download(self, request):
#         file = self._get_archive()
#         return sendfile(request, file.filename, attachment=True)
# 
#     def _get_archive(self):
#         directory = os.path.join(settings.MEDIA_ROOT, 'archives')
#         if not os.path.exists(directory):
#             os.makedirs(directory)
# 
#         filepath = os.path.join(
#             directory, '{gallery.date}-{gallery.pk}.zip'.format(gallery=self))
#         # Force the moment, don't use cache but recreate it each time. Anyway,
#         # store it in global private directory to be served by sendfile.
#         return self._generate_zipfile(filepath)
# 
#     def _generate_zipfile(self, filepath):
#         zf = zipfile.ZipFile(filepath, mode='w')
#         for image in self.images.all().prefetch_related('image'):
#             zf.write(
#                 image.image.file.path, os.path.basename(image.image.file.name))
#         zf.close()
#         return zf
# 
# Path: privagal/timeline/models.py
# class Timeline(AuthTokenPageMixin, Page):
# 
#     parent_page_types = []
#     subpage_types = ['gallery.Gallery']
# 
#     paginate_by = 20
# 
#     class Meta:
#         db_table = 'privagal_timeline'
# 
#     def get_context(self, request, *args, **kwargs):
#         context = super(Timeline, self).get_context(request, *args, **kwargs)
# 
#         search_query = request.GET.get('query', None)
#         context['search_query'] = search_query
# 
#         paginator, page = self.get_galleries(request, search_query)
#         context['page_obj'] = page
#         context['object_list'] = page.object_list
#         context['is_paginated'] = page.has_other_pages()
# 
#         return context
# 
#     def get_galleries(self, request, search_query):
#         qs = (
#             Gallery.objects
#             .live()
#             .prefetch_related(
#                 Prefetch(
#                     'images',
#                     queryset=ImageGallery.objects.select_related('image'),
#                 )
#             )
#             .order_by('-date')
#         )
# 
#         if search_query:
#             qs = qs.search(search_query, order_by_relevance=False)
# 
#         return paginate(request, qs, per_page=self.paginate_by)
# 
# Path: privagal/core/models.py
# class Token(models.Model):
#     """
#     Heavily copied from rest_framework.authtoken.models.Token
#     """
#     key = models.CharField(_("Key"), max_length=40, primary_key=True)
#     created = models.DateTimeField(_("Created"), auto_now_add=True)
# 
#     objects = TokenManager()
# 
#     class Meta:
#         db_table = 'privagal_token'
#         get_latest_by = "created"
# 
#     def save(self, *args, **kwargs):
#         if not self.key:
#             self.key = Token.generate_key()
#         return super(Token, self).save(*args, **kwargs)
# 
#     def __str__(self):
#         return self.key
# 
#     @classmethod
#     def generate_key(cls):
#         return binascii.hexlify(os.urandom(20)).decode()
# 
# Path: privagal/core/views.py
# class TokenCreateView(CreateView):
# 
#     def get_initial(self):
#         initial = super(TokenCreateView, self).get_initial()
#         initial['key'] = Token.generate_key()
#         return initial


from django.utils.translation import ugettext_lazy as _
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from wagtail.wagtailadmin.widgets import Button
from wagtail.wagtailcore import hooks
from privagal.gallery.models import Gallery
from privagal.timeline.models import Timeline
from .models import Token
from .views import TokenCreateView
# -*- coding: utf-8 -*-
from __future__ import unicode_literals






@hooks.register('register_page_listing_more_buttons')
def page_listing_button_link_token(page, page_perms, is_parent):
    if not isinstance(page, (Timeline, Gallery)):
        return

    token = Token.objects.singleton()
    if token:
        yield Button(
            _('Token link'),
            '{url}?token={key}'.format(url=page.full_url, key=token.key),
            attrs={'title': _('Copy this link address to share it.')},
            priority=0
        )


class TokenAdmin(ModelAdmin):

# Path: privagal/gallery/models.py
# class Gallery(AuthTokenPageMixin, Page):
#     date = models.DateField("Post date", default=timezone.now)
#     body = RichTextField(blank=True)
# 
#     content_panels = Page.content_panels + [
#         FieldPanel('date'),
#         FieldPanel('body', classname="full"),
#         InlinePanel('images', label=_('Images')),
#     ]
# 
#     parent_page_types = ['timeline.Timeline']
#     subpage_types = []
# 
#     class Meta:
#         db_table = 'privagal_gallery'
#         verbose_name = _("Gallery")
# 
#     def delete(self, *args, **kwargs):
#         with transaction.atomic():
#             # We need to call model instance method BEFORE deleting the
#             # instance itself to delete image in cascade. This is worst for
#             # performance than using QuerySet manager but it keep it stupid.
#             for image in self.images.all():
#                 image.delete()
#             super(Gallery, self).delete(*args, **kwargs)
# 
#     @property
#     def image_teaser(self):
#         return self.images.first()
# 
#     @property
#     def teaser(self):
#         return loader.render_to_string(
#             'gallery/gallery_teaser.html',
#             {
#                 PAGE_TEMPLATE_VAR: self,
#             },
#         )
# 
#     def serve_download(self, request):
#         file = self._get_archive()
#         return sendfile(request, file.filename, attachment=True)
# 
#     def _get_archive(self):
#         directory = os.path.join(settings.MEDIA_ROOT, 'archives')
#         if not os.path.exists(directory):
#             os.makedirs(directory)
# 
#         filepath = os.path.join(
#             directory, '{gallery.date}-{gallery.pk}.zip'.format(gallery=self))
#         # Force the moment, don't use cache but recreate it each time. Anyway,
#         # store it in global private directory to be served by sendfile.
#         return self._generate_zipfile(filepath)
# 
#     def _generate_zipfile(self, filepath):
#         zf = zipfile.ZipFile(filepath, mode='w')
#         for image in self.images.all().prefetch_related('image'):
#             zf.write(
#                 image.image.file.path, os.path.basename(image.image.file.name))
#         zf.close()
#         return zf
# 
# Path: privagal/timeline/models.py
# class Timeline(AuthTokenPageMixin, Page):
# 
#     parent_page_types = []
#     subpage_types = ['gallery.Gallery']
# 
#     paginate_by = 20
# 
#     class Meta:
#         db_table = 'privagal_timeline'
# 
#     def get_context(self, request, *args, **kwargs):
#         context = super(Timeline, self).get_context(request, *args, **kwargs)
# 
#         search_query = request.GET.get('query', None)
#         context['search_query'] = search_query
# 
#         paginator, page = self.get_galleries(request, search_query)
#         context['page_obj'] = page
#         context['object_list'] = page.object_list
#         context['is_paginated'] = page.has_other_pages()
# 
#         return context
# 
#     def get_galleries(self, request, search_query):
#         qs = (
#             Gallery.objects
#             .live()
#             .prefetch_related(
#                 Prefetch(
#                     'images',
#                     queryset=ImageGallery.objects.select_related('image'),
#                 )
#             )
#             .order_by('-date')
#         )
# 
#         if search_query:
#             qs = qs.search(search_query, order_by_relevance=False)
# 
#         return paginate(request, qs, per_page=self.paginate_by)
# 
# Path: privagal/core/models.py
# class Token(models.Model):
#     """
#     Heavily copied from rest_framework.authtoken.models.Token
#     """
#     key = models.CharField(_("Key"), max_length=40, primary_key=True)
#     created = models.DateTimeField(_("Created"), auto_now_add=True)
# 
#     objects = TokenManager()
# 
#     class Meta:
#         db_table = 'privagal_token'
#         get_latest_by = "created"
# 
#     def save(self, *args, **kwargs):
#         if not self.key:
#             self.key = Token.generate_key()
#         return super(Token, self).save(*args, **kwargs)
# 
#     def __str__(self):
#         return self.key
# 
#     @classmethod
#     def generate_key(cls):
#         return binascii.hexlify(os.urandom(20)).decode()
# 
# Path: privagal/core/views.py
# class TokenCreateView(CreateView):
# 
#     def get_initial(self):
#         initial = super(TokenCreateView, self).get_initial()
#         initial['key'] = Token.generate_key()
#         return initial


# Path: privagal/core/wagtail_hooks.py
from django.utils.translation import ugettext_lazy as _
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from wagtail.wagtailadmin.widgets import Button
from wagtail.wagtailcore import hooks
from privagal.gallery.models import Gallery
from privagal.timeline.models import Timeline
from .models import Token
from .views import TokenCreateView

# -*- coding: utf-8 -*-
from __future__ import unicode_literals






@hooks.register('register_page_listing_more_buttons')
def page_listing_button_link_token(page, page_perms, is_parent):
    if not isinstance(page, (Timeline, Gallery)):
        return

    token = Token.objects.singleton()
    if token:
        yield Button(
            _('Token link'),
            '{url}?token={key}'.format(url=page.full_url, key=token.key),
            attrs={'title': _('Copy this link address to share it.')},
            priority=0
        )


class TokenAdmin(ModelAdmin):

    model = Token