
from org.gvsig.tools.dynobject.impl import DefaultDynObject
from java.lang import Throwable

def _get(self, name):
  return self.getDynValue(name)
  
def _set(self, name, value):
  self.setDynValue(name, value)        

def _setValues(self,*args,**kwargs):
  if len(args)!=0:
    if len(args)!=2:
      raise IllegalArgumentException("Incorrent number of arguments ("+len(args)+"), expected 2.")
    self.__setitem__(args[0], args[1])
    return
  for k,v in kwargs.iteritems():
    self.__setitem__(k,v)

def _setitem(self,name, value):
  if self.getDynClass().getDynField(name) == None:
    raise KeyError(name)
  self.setDynValue(name, value)        

def _setattr(self,name, value):
  if self.getDynClass().getDynField(name) == None:
    raise AttributeError(self.__class__.__name__,name)
  self.setDynValue(name, value)        

def _getValues(self):
  items = dict()
  for name,value in self.iteritems():
    items[name] = value
  return items 

def _getitem(self,name):
  try:
    return self.getDynValue(name)
  except Throwable, ex:
    raise KeyError(name)

def _getattr(self,attributeName):
  # FIX console error when try to introspect feature object
  if attributeName == '__methods__':
      return dict()
  elif attributeName == '__members__':
      return self.getValues().keys()
  elif attributeName == '__dict__':
      return self.getValues()      
      
  try:
    v = getattr(self, attributeName, None)
    if v == None:
      v = self.getDynValue(attributeName)        
    return v
  except Throwable, ex:
    try:
        classname = self.getDynClass().getName()
    except:
        classname = ""
    raise AttributeError(classname,attributeName)

def _len(self):
  return len(self.getDynClass().getDynFields())

def _iteritems(self):
  fields = self.getDynClass().getDynFields()
  for field in fields:
    name = field.getName()
    value = self.get(field.getName())
    yield name,value
  
def _itervalues(self):
  fields = self.getDynClass().getDynFields()
  for field in fields:
    name = field.getName()
    value = self.get(field.getName())
    yield value
  
def _iterkeys(self):
  fields = self.getDynClass().getDynFields()
  for field in fields:
    name = field.getName()
    yield name

#---------
  
DefaultDynObject.setValues = _setValues
DefaultDynObject.getValues = _getValues
DefaultDynObject._get = _get
DefaultDynObject._set = _set

DefaultDynObject.__getitem__ = _getitem
DefaultDynObject.__setitem__ = _setitem
DefaultDynObject.__getattr__ = _getattr
DefaultDynObject.__setattr__ = _setattr
DefaultDynObject.__len__ = _len
DefaultDynObject.iteritems = _iteritems
DefaultDynObject.itervalues = _itervalues
DefaultDynObject.iterkeys = _iterkeys
