from Products.Formulator.StandardFields import ListField,StringField
from Products.Formulator.DummyField import fields
from Products.Formulator.Validator import SelectionValidator
from Products.Formulator.Errors import ValidationError
from Products.Formulator.FieldRegistry import FieldRegistry
from Products.Formulator.Widget import ListWidget
from Products.SilvaLayout.helpers import getAvailableSkins

from zLOG import LOG,WARNING

class SilvaLayoutListValidator(SelectionValidator):
    def validate(self, field, key, REQUEST):
        try:
            return SelectionValidator.validate(self, field, key, REQUEST)
        except ValidationError, e:
            if e.error_key == 'unknown_selection':
                #if this error key, then the layout skin isn't
                #installed.  So, default to the silvadefault skin
                skins = getAvailableSkins()
                newskin = None
                model = REQUEST.get('model',None)
                LOG('REQUEST',WARNING,REQUEST)
                if len(skins):
                    #return the id of the first skin
                    newskin = skins[0]
                    LOG('SilvaLayout',WARNING,'skin "%s" not found,  setting to alternate skin: %s.  model = %s'%(newskin,(model and '/'.join(model.getPhysicalPath()) or 'unknown')))
                else:
                    #return empty, which is "not set (acquire setting)
                    LOG('SilvaLayout',WARNING,'skin not found,  unable to locate alternate skin.  Setting to "acquire skin".  model = %s'%(model and '/'.join(model.getPhysicalPath()) or 'unknown'))
                    newskin = ''
                return newskin
            else:
                raise e
            
SilvaLayoutValidatorInstance = SilvaLayoutListValidator()

class SilvaLayoutListField(ListField):
    meta_type = "SilvaLayoutListField"
    validator = SilvaLayoutValidatorInstance

FieldRegistry.registerField(SilvaLayoutListField)
            
