
from java.lang import RuntimeException
from org.gvsig.fmap.dal.feature.impl import DefaultFeatureStore as JFeatureStore
from org.gvsig.fmap.dal.feature import FeatureQueryOrder
from java.lang import RuntimeException

def __getSchema(self):
  return self.getDefaultFeatureType()

def __features(self, expresion = None, sortby="", asc=True):
  if expresion == None and sortby =="":
    return self.getFeatureSet()         
  
  try:
    application = ApplicationLocator.getManager()
    datamanager =  application.getDataManager()
    query = self.createFeatureQuery()
    if sortby != "":
	order = FeatureQueryOrder()
	order.add(sortby, asc)
	query.setOrder(order)
    if expresion != None:
	query.setFilter(datamanager.createExpresion(expresion))
    fset = self.getFeatureSet(query)
  except Exception, e:
    return None
  return fset

def __iter(self):
  return self.getFeatureSet().__iter__()

def __len(self):
  return self.getFeatureSet().getSize()

def __append(self, *args, **kwargs):
  try:
    if not self.isEditing():
      self.super_edit() 

    if len(args) ==1:
      values.insert(args[0])
      return
    
    f = self.createNewFeature()
    
    if f == None:
      raise RuntimeException("Failed to create a new Feature")
      
    for k,v in kwargs.iteritems():
      f.set(k,v)
    self.insert(f)
      
  except Exception, ex:
    raise RuntimeException("Can't append values %s to layer %s (%s)" % (
      repr(kwargs), 
      self.getName(), 
      str(ex)
      )
    )

def __update(self, feature):
  if not self.isEditing():
      self.super_edit(self) 
  self.super_update(self,feature) 

def __edit(self):
  if not self.isEditing():
    self.super_edit()
    
def __commit(self):
  try:
    self.finishEditing()          
  except Exception, ex:
    self.abort()
    raise RuntimeException("Can't finish layer edition, cancelling changes. %s" % repr(ex))

def __abort(self):
  self.cancelEditing() 

def __call(self):
  return self    


#
# Save methods edit and update that are rewriten in python
#
JFeatureStore.super_edit = JFeatureStore.edit
JFeatureStore.super_update = JFeatureStore.update
#
# Inject new methods in the class JFeatureStore
#
JFeatureStore.getSchema = __getSchema
JFeatureStore.features = __features
JFeatureStore.append = __append
JFeatureStore.update = __update
JFeatureStore.edit = __edit
JFeatureStore.commit = __commit
JFeatureStore.abort = __abort
JFeatureStore.__call__ = __call
JFeatureStore.__iter__ = __iter
JFeatureStore.__len__ = __len



