# Path: privagal/gallery/factories.py
# class GalleryFactory(PageFactory):
# 
#     class Meta:
#         model = Gallery
# 
#     date = fuzzy.FuzzyDate(datetime.date(2016, 1, 1))
#     body = factory.LazyAttribute(
#         lambda x: "<p>{}</p>".format(faker.paragraph()))
# 
#     @factory.post_generation
#     def images(self, created, extracted, **kwargs):
#         """
#         Usage example:
#         >>> GalleryFactory(images__images=[ImageFactory()])
#         """
#         images = kwargs.pop('images', [])
#         if not images:
#             images = [ImageFactory() for i in range(0, 3)]
# 
#         self.images = [ImageGalleryFactory.build(page=self, image=i) for i in images]
# 
# 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/core/management/commands/genfactories.py
# IMAGES = [
#     'django.png',
#     'django-pony.png',
#     'django-pony-pink.jpg',
#     'wagtail.png',
#     'wagtail-space.png',
#     'python.jpg',
# ]


from django.core.management import call_command
from django.test import TestCase
from django.utils.six import StringIO
from wagtail.wagtailcore.models import Page
from wagtail.wagtailimages.models import get_image_model
from privagal.gallery.factories import GalleryFactory
from privagal.gallery.models import Gallery
from ..management.commands.genfactories import IMAGES

class GenerateFactoriesTestCase(TestCase):

    def test_generate(self):
        Page.objects.type(Gallery).delete()

        out = StringIO()
        call_command('genfactories', interactive=False, stdout=out)
        self.assertEqual(Page.objects.type(Gallery).count(), 5)
        self.assertIn(
            'Galleries have been generated successfully.\n',
            out.getvalue(),
        )

    def test_purge(self):
        for i in range(0, 3):
            GalleryFactory()

        out = StringIO()
        call_command(
            'genfactories', interactive=False, stdout=out, purge=True, limit=1)
        self.assertEqual(Page.objects.type(Gallery).count(), 1)
        self.assertEqual(Image.objects.all().count(), len(IMAGES))

    def test_limit(self):
        Page.objects.type(Gallery).delete()

        out = StringIO()
        call_command(
            'genfactories', interactive=False, stdout=out, limit=10)

# Path: privagal/gallery/factories.py
# class GalleryFactory(PageFactory):
# 
#     class Meta:
#         model = Gallery
# 
#     date = fuzzy.FuzzyDate(datetime.date(2016, 1, 1))
#     body = factory.LazyAttribute(
#         lambda x: "<p>{}</p>".format(faker.paragraph()))
# 
#     @factory.post_generation
#     def images(self, created, extracted, **kwargs):
#         """
#         Usage example:
#         >>> GalleryFactory(images__images=[ImageFactory()])
#         """
#         images = kwargs.pop('images', [])
#         if not images:
#             images = [ImageFactory() for i in range(0, 3)]
# 
#         self.images = [ImageGalleryFactory.build(page=self, image=i) for i in images]
# 
# 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/core/management/commands/genfactories.py
# IMAGES = [
#     'django.png',
#     'django-pony.png',
#     'django-pony-pink.jpg',
#     'wagtail.png',
#     'wagtail-space.png',
#     'python.jpg',
# ]


# Path: privagal/core/tests/test_commands.py
from django.core.management import call_command
from django.test import TestCase
from django.utils.six import StringIO
from wagtail.wagtailcore.models import Page
from wagtail.wagtailimages.models import get_image_model
from privagal.gallery.factories import GalleryFactory
from privagal.gallery.models import Gallery
from ..management.commands.genfactories import IMAGES


class GenerateFactoriesTestCase(TestCase):

    def test_generate(self):
        Page.objects.type(Gallery).delete()

        out = StringIO()
        call_command('genfactories', interactive=False, stdout=out)
        self.assertEqual(Page.objects.type(Gallery).count(), 5)
        self.assertIn(
            'Galleries have been generated successfully.\n',
            out.getvalue(),
        )

    def test_purge(self):
        for i in range(0, 3):
            GalleryFactory()

        out = StringIO()
        call_command(
            'genfactories', interactive=False, stdout=out, purge=True, limit=1)
        self.assertEqual(Page.objects.type(Gallery).count(), 1)
        self.assertEqual(Image.objects.all().count(), len(IMAGES))

    def test_limit(self):
        Page.objects.type(Gallery).delete()

        out = StringIO()
        call_command(
            'genfactories', interactive=False, stdout=out, limit=10)

        self.assertEqual(Page.objects.type(Gallery).count(), 10)