"""This module contains the test cases for the models of the ``media`` app"""

import os
import shutil
from mock import patch

from django.conf import settings

from ..models import PdfMedia

from .test_cases import MediaTestCase


class PresentationModelTestCase(MediaTestCase):
    """Test case for the ``Presentation`` model"""

    def test_pdf_should_return_the_pdf_media(self):
        """Test that the ``pdf`` property should return the pdf media"""

        self.assertEqual(self.presentation.pdf, self.pdf_media)
        self.assertEqual(self.presentation.restricted_pdf, self.restricted_pdf_media)


class PdfMediaModelTestCase(MediaTestCase):
    """Test case for the ``PdfMedia`` model"""

    @classmethod
    def setUpClass(cls):
        """Build the pdf to images folder path to use"""

        super().setUpClass()

        cls.images_path = cls.pdf_media.images_absolute_path

    def tearDown(self):
        """Remove file path and its content."""

        super().tearDown()

        # We remove folder and its path
        shutil.rmtree(self.images_path, ignore_errors=True)

    def test_images_absolute_path_should_output_the_right_path(self):
        """Test that the ``images_absolute_path`` correctly work"""

        images_absolute_path = os.path.normpath(
            os.path.join(
                settings.MEDIA_ROOT,
                settings.UPLOAD_TO[self.pdf_media._meta.object_name],
                '%(folder_prefix)s%(file_hash)s' % {
                    'folder_prefix': self.pdf_media.IMAGES_FOLDER_PREFIX,
                    'file_hash': self.pdf_media.file_hash
                }
            )
        )

        self.assertEqual(
            self.pdf_media.images_absolute_path,
            images_absolute_path
        )

    def test_is_generate_images_needed_when_folder_dont_exists(self):
        """Test ``is_generate_images_needed`` method when image folder don't exists"""

        needed, reason = self.pdf_media.is_generate_images_needed()

        self.assertTrue(needed)
        self.assertIsNone(reason)

    def test_is_generate_images_needed_needed_when_folder_exists(self):
        """Test ``is_generate_images_needed`` method when images folder exists"""

        os.makedirs(self.images_path)

        needed, reason = self.pdf_media.is_generate_images_needed()

        self.assertFalse(needed)
        self.assertIsInstance(reason, FileExistsError)

    def test_generate_images_not_async_should_call_generate_images_from_pdf(self):
        """Test that the ``generate_images`` method works in synchronous mode."""

        # We'll only check if the ``generate_images_from_pdf`` function is called
        with patch.object(PdfMedia, 'generate_images') as patched:
            self.pdf_media.save()

        # We should have one call to ``PdfMedia.generate_images``
        patched.assert_called_once_with(
            async=True
        )


