package scripting;

import org.gvsig.fmap.dal.feature.FeatureType;
import org.gvsig.fmap.mapcontext.layers.FLayer;

public class gvsig {

  /**
   * Returns a new and empty attributes definition. 
   *
   * @deprecated use createFeatureType instead
   */
  public static FeatureType createSchema() {
    return null;
  }
  
  /**
   * Returns a new and empty attributes definition based in an 
   * existing schema.
   *
   * @deprecated use createFeatureType instead
   */
  public static FeatureType createSchema(FeatureType schema) {
    return null;
  }
  
  /**
   * Returns a new and empty attributes definition. 
   *
   */
  public static FeatureType createFeatureType() {
    return null;
  }
  
  /**
   * Returns a new and empty attributes definition based in an 
   * existing schema.
   *
   */
  public static FeatureType createFeatureType(FeatureType schema) {
    return null;
  }

  /**
    * Create a new layer with the specified parameters.
    *
    * The paramaters "..." are used to connect to the server type and
    * create the layer.
    *
    * Valid values of server type are:
    * - FilesystemExplorer
    * - TODO
    *
    * Valid values of layer type are:
    * - Shape
    * - TODO
    *
    * Excamples of use:
    * TODO
    *
    * @param schema the schema to use to create la layer.
    * @param serverType The server type (filesystem, BBDD, ...)
    * @param layerType The layer type to create (Shape, ...)
    * 
    */
  public static FLayer creaetLayer(FeatureType schema, String serverType, String layerType, ...) {
    return null;
  }
  
  /**
    * Create a new layer with the specified parameters.
    *
    * Use as default serverType the "FilesystemExplorer".
    *
    */
  public static FLayer creaetLayer(FeatureType schema, String layerType, ...) {
    return null;
  }

  /**
    * Load an existing shape file in the current view.
    *
    * @param path path to the shape file to load
    * @param projection to use to load the shape file
     * @return 
    *
    */
  public static FLayer loadShapeFile(String path, String projection) {
    return null;
  }
  
  /**
    * Load an existing shape file in the current view.
    *
    * Use as default projection "CRS:84"
    *
    * @param path path to the shape file to load
     * @return 
    * 
    */
  public static FLayer loadShapeFile(String path) {
    return null;
  }
  
  /**
    * Load an existing layer and return it.
    *
    * Valid values of layer type are:
    * - Shape
    * - TODO
    *
    * @param layerType 
     * @param <error> 
     * @return  
    * 
    */
  public static FLayer loadLayer(String layerType, ...) {
    return null;
  }
  
  

  
  def createShape(definition, filename, geometryType, CRS="CRS:84"):
  """
  Return new shape layer 
  :param definition: layer data definition
  :type definition: Schema
  :param filename: absolute path for shape files. 
  :type filename: string
  :param geometryType: geometry type for shape
  :type geometryType: string
  :return: new shape layer
  :rtype: Layer
  """
  return createLayer(
    definition, 
    "FilesystemExplorer", 
    "Shape", 
    shpFile=filename, 
    CRS=CRS,
    geometryType = geometryType
  )

def createTable(schema, servertype, tableType=None, **parameters):
  """Creates a new Table document"""
  if tableType == None:
    tableType = servertype
    servertype = "FilesystemExplorer"

  try:
    application = ApplicationLocator.getManager()
    datamanager =  application.getDataManager()
    
    server_parameters = datamanager.createServerExplorerParameters(servertype)
    copyToDynObject(parameters, server_parameters)

    server = datamanager.openServerExplorer(servertype, server_parameters)
    
    store_parameters = server.getAddParameters(tableType)
    copyToDynObject(parameters, store_parameters)
    store_parameters.setDefaultFeatureType(schema())
    
    server.add(tableType, store_parameters, True)

    store = datamanager.openStore(tableType, store_parameters)
    
    return store
  
  except Throwable, ex:
    raise RuntimeException("Can't create table, "+ str(ex))
  
def createDBF(definition, DbfFile, CRS="CRS:84"):
  """
  Creates a new dbf document 
  :param definition: layer data definition
  :type definition: Schema
  :param DbfFile: absolute path for shape files. 
  :type DbfFile: string
  :return: new dbf
  :rtype: Table    
  """
  return createTable(
    definition, 
    "FilesystemExplorer", 
    "DBF", 
    DbfFile=DbfFile, 
    CRS=CRS,
  )


#=====================#
# Simbology Functions #
#=====================#  
COLORS = {
    'black': Color.black,
    'blue': Color.blue,
    'cyan': Color.cyan,
    'darkGray': Color.darkGray,
    'gray': Color.gray,
    'green': Color.green,
    'lightGray': Color.lightGray,
    'magenta': Color.magenta,
    'orange': Color.orange,
    'pink': Color.pink,
    'red': Color.red,
    'white': Color.white,
    'yellow': Color.yellow,
}
  
def simplePointSymbol(color=None):
  """
  Returns simple point symbol using parameter color. If no color 
  use a ramdom color
  :param color: String color name or Java awt Color
  :return: gvSIG point symbol
  """
  if isinstance(color, str) and COLORS.has_key(color.lower()):
    color = COLORS.get(color)
    
  if not isinstance(color, Color):
      color = getDefaultColor()
      
  return MapContextLocator.getSymbolManager().createSymbol(
        Geometry.TYPES.POINT, color)

def simpleLineSymbol(color=None):
  """
  Returns simple line symbol using parameter color. If no color use a 
  ramdom color  
  :param color: String color name or Java awt Color
  :return: gvSIG line symbol
  
  """
  if isinstance(color, str) and COLORS.has_key(color.lower()):
    color = COLORS.get(color)

  if not isinstance(color, Color):
      color = getDefaultColor()
      
  return MapContextLocator.getSymbolManager().createSymbol(
        Geometry.TYPES.CURVE, color)

def simplePolygonSymbol(color = None):
  """
  Returns simple polygon symbol using parameter color. If no color 
  use a ramdom color.  
  :param color: String color name or Java awt Color
  :return: gvSIG polygon symbol
  """
  if isinstance(color, str) and COLORS.has_key(color.lower()):
    color = COLORS.get(color)

  if not isinstance(color, Color):
      color = getDefaultColor()
  
  return MapContextLocator.getSymbolManager().createSymbol(
        Geometry.TYPES.SURFACE, color)
  

#=========================================#
# gvSIG Application Preferences Functions #
#=========================================#  

def getDataFolder():
  """
  Returns gvSIG data folder. This folder is defined in application 
  preferences. If is not defined returns None.
  """
  return Preferences.userRoot().node("gvsig.foldering").get('DataFolder', None)
  
def getProjectsFolder():
  """
  Returns gvSIG projects folder. This folder is defined in application 
  preferences. If is not defined returns None.
  """
  return Preferences.userRoot().node("gvsig.foldering").get(
        'ProjectsFolder', None)

def getColorFromRGB(r, g, b, a=None):
  """
  Returns an sRGB color with the specified red, green, blue, and alpha 
  (optional) values in the range (0 - 255).
  """
  if a:
    color = Color(r, g, b, a)
  else:
    color = Color(r, g, b)
  
  return color
  
def getDefaultColor(c = None):
  """Returns gvsig default symbol fill color or ramdom color"""
  if MapContextLocator.getSymbolManager().isDefaultSymbolFillColorAleatory():
    color = Color(random.randint(0-255), 
                random.randint(0-255), 
                random.randint(0-255)
            )
  else:
    sp = MapContextLocator.getSymbolManager().getSymbolPreferences()
    color = sp.getDefaultSymbolFillColor()    

  return color  

}
