from OFS.SimpleItem import SimpleItem
from plone import api
from ploneintranet.docconv.client.interfaces import IBlobFileWrapper
from ploneintranet.docconv.client.interfaces import IPreviewSettings
from Products.Five import BrowserView
from zExceptions import NotFound
from zope.interface import implementer
from zope.publisher.interfaces.browser import IBrowserPublisher


@implementer(IBlobFileWrapper, IBrowserPublisher)
class BlobFileWrapper(SimpleItem):
    def __init__(self, fileobj, settings, filepath, request):
        self.context = fileobj
        self.settings = settings
        self.filepath = filepath
        self.request = request

    def browserDefault(self, request):
        return self, ("@@view",)


class SmallView(BrowserView):

    possible_keys = ("large/dump_1.svg", "small/dump_1.gif")

    def __call__(self):
        settings = IPreviewSettings(self.context)
        # Try to get the svg preview if possible,
        # otherways fallback to the default one
        for key in self.possible_keys:
            try:
                view = api.content.get_view(
                    "view",
                    BlobFileWrapper(self.context, settings, key, self.request),
                    self.request,
                )
                return view()
            except KeyError:
                pass
        raise NotFound
