import zope.component
import zope.interface
import z3c.form
from z3c.json.converter import JSONWriter
from Products.Five.browser import BrowserView
from utils import dict2dynatree
from utils import lookupVocabulary
import interfaces

from Products.ATVocabularyManager import NamedVocabulary

class FieldVocabDynatreeJsonView(BrowserView):
    
    def __call__(self):
        fieldname = self.request.get('fieldname')
        #field = self.context.schema[fieldname]
        # TODO: This is hardcoded, Incredibly stupid, needs to change.
        atv = NamedVocabulary('staralliance-productcategories')
        tree = atv.getVocabularyDict(self.context)
        selected = self.request.get('selected', []).split('|')
        return JSONWriter().write(dict2dynatree(tree, selected, 
                                                True,
                                                False))
    
class DynatreeWidget(z3c.form.browser.text.TextWidget):
    """
    A text field widget with a dynatree javascript vocabulary to determine the
    value.
    """
    zope.interface.implementsOnly(interfaces.IDynatreeWidget)
    klass = u'dynatree-widget'
    selectMode = 1
    minExpandLevel = 0
    rootVisible = False
    autoCollapse = False
    leafsOnly = True
    showKey = False
    atvocabulary = None
    
    def dynatree_parameters(self):
        result = [('%s,%s' % (parameter, getattr(self, parameter))) 
                  for parameter in ['selectMode',
                                    'minExpandLevel',
                                    'rootVisible', 
                                    'autoCollapse']]
        result.append('title,%s' % self.label)
        return '/'.join(result)
    
    def dynatree_value(self, value):
        if isinstance(value, basestring):
            return value
        if isinstance(value, (tuple, list)):
            return '|'.join(value)
        return ''     

@zope.component.adapter(zope.schema.TextLine, z3c.form.interfaces.IFormLayer)
@zope.interface.implementer(z3c.form.interfaces.IFieldWidget)
def DynatreeFieldWidget(field, request):
    """ IFieldWidget factory for DynatreeWidget 
    """
    return z3c.form.widget.FieldWidget(field, DynatreeWidget(request))


@@ -332,21 +332,17 @@
 rView):%0A
-    
 %0A
+
     def 
@@ -767,17 +767,16 @@
 elected,
- 
 %0A       
@@ -878,21 +878,17 @@
 False))%0A
-    
 %0A
+
 class Dy
@@ -1290,21 +1290,17 @@
  = None%0A
-    
 %0A
+
     def 
@@ -1393,17 +1393,16 @@
 meter)))
- 
 %0A       
@@ -1548,17 +1548,16 @@
 isible',
- 
 %0A       
@@ -1681,21 +1681,17 @@
 result)%0A
-    
 %0A
+
     def 
@@ -1883,21 +1883,16 @@
 eturn ''
-     
 %0A%0A@zope.
@@ -2062,24 +2062,24 @@
 , request):%0A
+
     %22%22%22 IFie
@@ -2113,17 +2113,16 @@
 eeWidget
- 
 %0A    %22%22%22

remove trailing spaces