
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
from org.gvsig.app import ApplicationLocator
from org.gvsig.tools.evaluator import Evaluator

#
# Save methods edit and update that are rewriten in python
#
super_edit = JFeatureStore.edit
super_update = JFeatureStore.update

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:
      if isinstance(expresion,Evaluator):
        query.setFilter(expresion)
      else:
        query.setFilter(datamanager.createExpresion(expresion))
    fset = self.getFeatureSet(query)
    return fset
  except Exception, e:
    return None

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.edit()

    if len(args) ==1:
      if not isinstance(args[0], dict):
        raise ValueError("Argument should be a dict")
      if kwargs == None:
        kwargs = args[0]
      else:
        kwargs.update(args[0])

    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.edit()
  super_update(self, feature)

def __edit(self, mode=JFeatureStore.MODE_FULLEDIT):
  if not self.isEditing():
    super_edit(self, mode)

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


#
# 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



