
__author__ = """Victor Acevedo Royer <vacevedor@gvsig.com>, 
<vacevedor@gmail.com>"""

__docformat__ = 'plaintext'

import gvsig 
from gvsig import commonsdialog 



def main(): 
  """
  This script runs all the features of the active layer, and calculates the 
  maximum and minimum elevation these, and with this:
    - Shows a message informing the user which are
  
  If no ELEVATION field shows a message and finish script execution.
  
  In the data folder can be found polygons_with_elevation layer used
  for testing with this script.
  """
  
  #
  #Invoke gvsig.currentLayer function to get active layer
  #If not view or active layer in view raise RuntimeException
  layer = gvsig.currentLayer()
  
  #
  #Invoke layer.getSchema method to get layer definition data 
  schema = layer.getSchema()
  
  #
  #Invoke schema.get method to get ELEVATION field or None
  field = schema.get('ELEVATION', None)
  
  #
  #Check if field exist
  if not field:
      #If not shows message and finish
      text = '"ELEVATION" field must exist in the active layer.\nFinish script'
      title = "ERROR"
      message_type = commonsdialog.WARNING
      commonsdialog.msgbox(text, title, message_type)
      return
  
  emax = 0.0
  emin = 0.0

  #
  # Gets features using layer.features method
  features = layer.features()
  
  #
  #Runs layer features
  for feature in features:
    # 
    # Cheacks if current feature ELEVATION is higher than calculated. 
    # If so stored current ELEVATION value
    if feature.ELEVATION > emax :
      emax = feature.ELEVATION
    #
    # Same but with minimum ELEVATION
    if feature.ELEVATION < emin or emin ==0.0:
      emin = feature.ELEVATION
  #
  # Finally show results in a msgbox message.
  text = "Maximum Elevation=%s, Minumun Elevation=%s" % (emax, emin)
  title = "Maximun and minumum values"
  message_type = commonsdialog.IDEA
  
  commonsdialog.msgbox(text, title, message_type)

