from plone import api
from Products.Five.browser import BrowserView


class PrintPreview(BrowserView):
    """Render html suitable for print

    This can be dumped to the file system and converted to a pdf
    with weasyprint or libreoffice
    """

    _plone_css_keys = (
        "plone.bundles/ploneintranet-workspace-styles.csscompilation",
        "plone.bundles/ploneintranet.csscompilation",
    )
    _custom_css = """
        tr, td, th, tbody, thead, tfoot {
            page-break-inside: avoid !important;
        }
        html {
            background-color: #fff;
        }
        body {
            background-color: #fff;
            font-size: 14px;
        }
        article.content {
            margin-left: 2cm;
            margin-right: 4cm;
            margin-top: 3cm;
            margin-bottom: 3cm;
        }
    """

    def get_styles(self):
        """Return a list of CSS rules styles that will be dumped directly in the html"""
        styles = []
        for key in self._plone_css_keys:
            value = api.portal.get_registry_record(key, default="")
            if value:
                resource = self.context.restrictedTraverse(value)
                with open(resource.path) as f:
                    styles.append(f.read())

        if self._custom_css:
            styles.append(self._custom_css)
        return styles
