from plone.memoize.view import memoize
from plone.namedfile.file import NamedBlobImage
from ploneintranet.docconv.client.browser.base import CommandView

import logging
import os

logger = logging.getLogger(__name__)

try:
    from sh import ffmpegthumbnailer
except ImportError:
    # Missing
    logger.error(
        "No `ffmpegthumbnailer` command in your PATH. "
        "Preview generation will not work for video links."
    )
    ffmpegthumbnailer = None


class LeadImage(CommandView):

    command = ffmpegthumbnailer

    @property
    @memoize
    def arguments(self):
        return [
            "-s",
            "0",
            "-i",
            self.context.remoteUrl,
            "-o",
            os.path.join(self.get_tempdir().name, "poster.jpg"),
        ]

    def is_needed(self):
        """This command is not needed if we have a lead image
        this lead image and the lead image is a custom _from_url attribute set
        which is equal to the context remoteUrl
        """
        if not getattr(self.context, "image", None):
            return True
        _from_url = getattr(self.context.image, "_from_url", "")
        if not _from_url:
            return False
        if _from_url == self.context.remoteUrl:
            return False
        return True

    def post_command(self):
        """Get the produced poster jpeg and save it as a lead image"""
        oufile = self.arguments[-1]
        with open(oufile, "rb") as fp:
            self.context.image = NamedBlobImage(data=fp.read(), filename="poster.jpg")
            self.context.image._from_url = self.context.remoteUrl

    def __call__(self, force=False):
        self.run(force=force)
        return "OK"
