# encoding: utf-8

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
    - Select the geometries associated with maximum and minimum elevation. 
  
  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
  fmax = None
  fmin = None
  #
  # 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 and the feature instance
    if feature.ELEVATION > emax :
        emax = feature.ELEVATION
        fmax = feature.getCopy()
      
    # Same but with minimum ELEVATION
    if feature.ELEVATION < emin or emin ==0.0:
        emin = feature.ELEVATION
        fmin = feature.getCopy()
  #
  # Selects features in the layer.
  if fmax!=None:
    layer.select(fmax)
  if fmin!=None:
    layer.select(fmin)
  #
  # 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)

