from plone import api
from ploneintranet import api as pi_api
from ploneintranet.asynctasks.celeryconfig import ASYNC_ENABLED
from ploneintranet.asynctasks.tasks import GenerateLeadImage
from ploneintranet.asynctasks.tasks import GeneratePDF
from ploneintranet.asynctasks.tasks import GeneratePoster
from ploneintranet.attachments.attachments import IAttachmentStoragable
from ploneintranet.attachments.utils import IAttachmentStorage
from ploneintranet.docconv.client.interfaces import IPreviewSettings
from zope.globalrequest import getRequest

import logging

try:
    from sh import ffmpegthumbnailer
except ImportError:
    # Missing
    ffmpegthumbnailer = None


log = logging.getLogger(__name__)


def generate_pdf(obj, event=None, purge=False, countdown=10):
    """Generates the pdf version of the given content
    by dispatching to the async service
    If purge is True, remove old previews before creating the new ones
    """
    file_types = api.portal.get_registry_record(
        "ploneintranet.docconv.file_types", default=["File"]
    )
    html_types = api.portal.get_registry_record(
        "ploneintranet.docconv.html_types", default=["Document"]
    )

    if hasattr(obj, "portal_type") and obj.portal_type not in file_types + html_types:
        log.info(
            "Skipping documentconversion for %s (unsupported type)"
            % obj.absolute_url(1)
        )
        return

    if ASYNC_ENABLED:
        if purge:
            pi_api.previews.purge_previews(obj)
        IPreviewSettings(obj).converting = True
        log.debug("> Generate PDF - ASYNC Mode has been selected.")
        generator = GeneratePDF(obj, getRequest())
        log.info("Starting PDF generation with a delay of %s secs", countdown)
        generator(countdown=countdown)
    else:
        log.debug("generate_pdf - sync mode")
        pi_api.previews.generate_pdf(obj)


def handle_file_creation(obj, event=None, asynchronous=True):
    """Need own subscriber as cdv insists on checking for its
    custom layout. Also we want our own async mechanism.
    """
    if obj.portal_type == "Image":
        return
    request = getRequest() or {}
    event_key = "ploneintranet.previews.handle_file_creation"
    enabled = request.get(event_key, True)  # default is enabled
    if not enabled:
        log.debug("%s disabled", event_key)
        return

    if asynchronous:
        log.debug("handle pdf creation - async mode")
        generate_pdf(obj)
    else:
        log.debug("handle pdf creation - sync mode")
        pi_api.previews.generate_pdf(obj)


def generate_attachment_preview_images(obj):
    if not IAttachmentStoragable.providedBy(obj):
        return
    attachment_storage = IAttachmentStorage(obj)
    for att_id in attachment_storage.keys():
        attachment = attachment_storage.get(att_id)
        if not pi_api.previews.has_previews(attachment):
            log.debug(
                "generate_attachment_preview_images" " - generating attachment preview"
            )
            generate_pdf(attachment)


def content_added_in_workspace(obj, event):
    if obj.portal_type == "Plone Site":
        # Starting with Plone 6, the Plone Site is a dexterity container.
        # We do not want to generate a PDF when adding a Plone Site.
        return
    event_key = "ploneintranet.previews.content_added_in_workspace"
    request = getRequest() or {}
    enabled = request.get(event_key, True)  # default is enabled
    if not enabled:
        log.debug("%s disabled", event_key)
        return

    log.debug("content_added_in_workspace - calling generate_pdf")
    generate_pdf(obj)


def content_edited_in_workspace(obj, event):
    request = getRequest()
    if not hasattr(request, "form"):
        return

    event_key = "ploneintranet.previews.content_edited_in_workspace"
    enabled = request.get(event_key, True)  # default is enabled
    if not enabled:
        log.debug("%s disabled", event_key)
        return

    try:
        request_url = request.getURL()
    except AttributeError:
        request_url = ""
    _get = request.form.get
    if (
        _get("file")
        or _get("form.widgets.IFileField.file")
        or any(
            getattr(desc, "attributes", ()) == ("IRichTextBehavior.text",)
            for desc in event.descriptions
        )
        or _get("text")
        or request.get("method") == "PUT"
        or request_url.endswith("revertversion")
        or "@@collabora-wopi" in request_url
    ):
        generate_pdf(obj)


def generate_video_poster(obj, event):
    """Make a poster image for video files"""
    if not ffmpegthumbnailer:
        return
    if not (obj.content_type() or "").startswith("video/"):
        return
    GeneratePoster(obj)(countdown=5)


def video_link_lead_image(obj, event):
    """Make a default lead image for video links"""
    if not ffmpegthumbnailer:
        return
    if not (obj.content_type() or "") == "text/x-uri-video":
        return
    GenerateLeadImage(obj)(countdown=5)
