from plone.autoform.interfaces import IFormFieldProvider
from plone.namedfile import field as namedfile
from plone.rfc822.interfaces import IPrimaryField
from plone.supermodel import model
from zope.component import adapter
from zope.interface import alsoProvides
from zope.interface import implementer
from zope.interface import provider
from zope.interface.interface import Interface


class IFileFieldMarker(Interface):
    """Marker interface for IFileField behaviors."""


@provider(IFormFieldProvider)
class IFileField(model.Schema):
    """We need to override the default file field so that we can interpret an
    empty string as NOT_CHANGED.
    """

    file = namedfile.NamedBlobFile(title="File", description="", required=True)


# The equivalent of setting marshal:primary="true" on the field in the schema:
alsoProvides(IFileField["file"], IPrimaryField)


@implementer(IFileField)
@adapter(IFileFieldMarker)
class FileField:
    def __init__(self, context):
        self.context = context

    @property
    def file(self):
        return self.context.file

    @file.setter
    def file(self, value):
        self.context.file = value

    @property
    def is_audiotype(self):
        ct = getattr(self.context.file, "contentType", "")
        return "audio/" in ct

    @property
    def is_videotype(self):
        ct = getattr(self.context.file, "contentType", "")
        return "video/" in ct
