"""This module holds exports for ``photostories`` app."""

import io
import zipfile


class StripExportError(Exception):
    """Error raised during strips export."""

    pass


class StripsArchive:  # pylint: disable=missing-param-doc,missing-type-doc
    """List of strips in zip format.

    Parameters
    ----------
    strips: dict(list)
        A dictionary with strip as key and these photos as value.
    zip_buffer: io.BytesIO
        The zip buffer.
    content_type: str
        The content type of the archive.
    extension: str
        The extension to add to the archive file.

    """

    content_type = 'application/zip'
    extension = 'zip'

    def __init__(self, strips):
        """Initialize the strips archive.

        Parameters
        ----------
        strips: dict(list)
            A dictionary with strip as key and these photos as value.

        """

        self.strips = strips
        self.zip_buffer = io.BytesIO()
        self.create()

    def create(self):
        """Create an archive containing provided strips."""

        if not self.strips:
            raise StripExportError('No strips to export.')

        with zipfile.ZipFile(self.zip_buffer, 'w') as zip_file:

            # For each strip, rename each photo file and add it to the zip archive
            for strip, photos_path in self.strips.items():
                for index, path in enumerate(photos_path):
                    zip_file.write(
                        path,
                        '%(name)s//%(index)d.jpg' % {
                            'name': strip.name,
                            'index': index,
                        }
                    )

    @property
    def data(self):
        """Get the data of the strip archive.

        Returns
        -------
        bytes

        """

        return self.zip_buffer.getvalue()
