# Copyright (c) 2005 Infrae. All rights reserved.
# See also LICENSE.txt

import sys
import random

# Zope 3
from zope.interface import implements

from zope.app.container.interfaces import INameChooser

from zope.app import zapi
from zope.app.catalog.interfaces import ICatalog
from zope.app.folder import Folder
from zope.app.exception.interfaces import UserError

# documentlibrary
import interfaces

class DocumentFolder(Folder):

    implements(interfaces.IDocumentFolder)
            
class RandomNameChooser:
    
    implements(INameChooser)
    
    def __init__(self, context):
        self.context = context
    
    def chooseName(self, name, obj):
        if name:
            return name
        while True:
            nr = random.randrange(sys.maxint)
            name = u'%010d' % nr
            if not nr in self.context:
                return name

    def checkName(self, name, obj):
        try:
            nr = long(name)
        except ValueError:
            raise UserError(u'Name should be a number')
            
class DocumentNameChooser:

    implements(INameChooser)

    def __init__(self, context):
        self.context = context

    def chooseName(self, name, obj):
        if name:
            return name
        catalog = zapi.getUtility(ICatalog, 'document_catalog')
        while True:
            nr = random.randrange(sys.maxint)
            name = u'%010d' % nr
            has_name = catalog.searchResults(name=(name, name))
            if not len(has_name):
                return name

    def checkName(self, name, obj):
        try:
            nr = long(name)
        except ValueError:
            raise UserError(u'Name should be a number')
        
