"""This module holds the models of the ``pdf-reporting`` app."""

from django.http.response import HttpResponse
from django.views.generic.base import ContextMixin, TemplateResponseMixin

from mtp.apps.common.views_utils import ExportFileMixin, RestrictToSuperuserOrTrainerMixin

from .pdf_report import PDFReport


class PDFReportMixin(ExportFileMixin, RestrictToSuperuserOrTrainerMixin,
                     TemplateResponseMixin, ContextMixin):
    """Mixin which allow to generate a PDF report.

    Attributes
    ----------
    response_class : Response
        The response class used to render the response.

    Notes
    -----
    This mixin depends on `ContextMixin` and we provide the computed context data in pdf report.
    It means that we can use multiple inheritance to compute this context data.

    Examples
    --------
    >>> class CertificationResultsView(PDFReportMixin, CertificationDetailView):
    >>>     pass

    In this example, the context data computed in ``CertificationDetailView`` will provide to
    pdf report.

    """

    response_class = HttpResponse

    def get_pdf_report(self, context_data):
        """Get the pdf report.

        Parameters
        ----------
        context_data : dict
            The context data to pass in pdf template.

        Returns
        -------
        PDFReport
            The pdf report configured with the provided template_name and the view context data.

        """

        return PDFReport(template_name=self.template_name, context_data=context_data)

    def render_to_response(self, context, **response_kwargs):
        """Render the PDF report to download.

        Parameters
        ----------
        context : dict
            The context data used to render the pdf template.

        Returns
        -------
        HttpResponse
            The response containing the pdf report.

        """

        pdf = self.get_pdf_report(context)

        response = self.response_class(content_type=pdf.content_type, **response_kwargs)
        response.write(pdf.get_file_content())
        filename = self.get_slugified_filename()
        response['Content-Disposition'] = 'attachment; filename=%s.pdf' % filename

        return response
