from zope.app import zapi
from zope.app.form.interfaces import ConversionError
from zope.app.form.browser.widget import renderElement

from hurry.file.browser import SessionFileWidget, DownloadWidget

from documentlibrary.core import interfaces

class FileWidget(SessionFileWidget):

    displayWidth = 55
    
    def _toFieldValue(self, input):
        result = super(FileWidget, self)._toFieldValue(input)
        if result == self.context.missing_value:
            return result

        file_validation = zapi.getUtility(interfaces.IFilenameValidation)
        try:
            file_validation.checkFilename(result.filename)
        except interfaces.ForbiddenFilenameError, e:
            raise ConversionError(unicode(e))

        return result

class FileUploadDownloadWidget(FileWidget, DownloadWidget):
    def __call__(self):
        # first render the normal upload information
        result = FileWidget.__call__(self)
        # now show the download link
        result += renderElement('br')
        result += DownloadWidget.__call__(self)
        return result
