import os
import pytz
# Zope 3
from persistent import Persistent
from zope.interface import implements
from zope.schema.vocabulary import SimpleVocabulary

from zope.app.container.contained import Contained

# documentlibrary

from documentlibrary.core import interfaces

class CustomText(Persistent, Contained):
    
    implements(interfaces.ICustomText)

    def __init__(self, frontpage_text=u'', help_url=u''):
        self.frontpage_text = frontpage_text
        self.help_url = help_url

class MaximumRetentionPeriod(Persistent, Contained):
    
    implements(interfaces.IMaximumRetentionPeriod)

    def __init__(self, maximum_retention_period=730):
        self.maximum_retention_period = maximum_retention_period

class FilenameValidation(Persistent, Contained):
    
    implements(interfaces.IFilenameValidation)

    def __init__(self):
        self._forbidden_extensions = {}
        self.forbidden_spaces = True
        
    def _set_forbidden_extensions(self, value):
        if value is None:
            self._forbidden_extensions = {}
            return
        value = value.strip()
        extensions = value.split()
        forbidden_extensions = {}
        for extension in extensions:
            forbidden_extensions[extension] = None
        self._forbidden_extensions = forbidden_extensions

    def _get_forbidden_extensions(self):
        return ' '.join(sorted(self._forbidden_extensions.keys()))

    forbidden_extensions = property(_get_forbidden_extensions,
                                    _set_forbidden_extensions)

    def checkFilename(self, filename):
        # check for the existence of spaces
        path, filename = pathsplit(filename)
        if self.forbidden_spaces:
            if filename.find(' ') != -1:
                raise interfaces.ForbiddenFilenameError(
                    'Filename contains spaces, please use \'-\' instead.')
        # check for use of forbidden extension
        dummy, extension = os.path.splitext(filename)
        if extension in self._forbidden_extensions:
            raise interfaces.ForbiddenFilenameError(
                "Filetype forbidden: %s" % extension)
        
def pathsplit(filename):
    """A os.path.split that also works for windows paths with backslashes.
    """
    # XXX simplistic implementation
    filename = filename.replace('\\', '/')
    return os.path.split(filename)

class Timezone(Persistent, Contained):
    
    implements(interfaces.ITimezone)
    
    def __init__(self, name='UTC'):
        self.timezone_name = name

def timezoneVocabulary(context):
    return SimpleVocabulary.fromValues(pytz.common_timezones)
