

from org.gvsig.fmap.dal.feature.impl import DefaultEditableFeatureType as JEditableFeatureType

from org.gvsig.fmap.dal import DataTypes
from org.gvsig.app import ApplicationLocator
from java.lang import RuntimeException

import featuretype

def _append(self, name, type, size=None, default=None, precision=4):
  application = ApplicationLocator.getManager()
  datamanager =  application.getDataManager()
  dataTypes = application.getDataTypesManager()
  if isinstance(type, str):
    try:
      type = dataTypes.getType(type) # dataType constant value from string
      type = dataTypes.get(type)
    except:
      raise RuntimeError(
	  "Feature Property Data type (%s) is not valid.  name=%s, type=%s, size=%s, default=%s)" % (
	      type,
	      name,
	      type,
	      size,
	      default
	  )
      )
  elif isinstance(type, int):
    try:
      type = dataTypes.get(type)
    except:
      raise RuntimeError(
	  "Data type (%s) is not valid.  name=%s, type=%s, size=%s, default=%s)" % (
	      type,
	      name,
	      type,
	      size,
	      default
	  )
      )
  elif not isinstance(type,DataType):
      raise RuntimeError(
	  "Data type (%s) is not valid.  name=%s, type=%s, size=%s, default=%s)" % (
	      type,
	      name,
	      type,
	      size,
	      default
	  )
      )

  attribute = self.add(name, type.getType())

  if size != None:
    attribute.setSize(size)

  if default != None:
    attribute.setDefaultValue(default)

  if precision != None and type.getType() in (DataTypes.DOUBLE, DataTypes.FLOAT):
    attribute.setPrecision(precision)

  if type.getType() == DataTypes.GEOMETRY and self.getDefaultGeometryAttributeName()==None:
    self.setDefaultGeometryAttributeName(name)

  return attribute

def _setDefaultGeometryType(self, type, dimension):
    self.getDefaultGeometryAttribute().setGeometryType(type, dimension)
#
# Inject new methods in the class JEditableFeatureType
#

JEditableFeatureType.setDefaultGeometryType = _setDefaultGeometryType
JEditableFeatureType.__call__ = featuretype._call
JEditableFeatureType.__iter__ = featuretype._iter
JEditableFeatureType.__len__ = featuretype._len
JEditableFeatureType.get = featuretype._get
JEditableFeatureType.getAttrNames = featuretype._getAttrNames
JEditableFeatureType.append = _append

