
from gvsig import *
from commonsdialog import *

"""
Para probar este ejemplo cargue la capa MANZANAS_POB de la carpeta
data y seleccionela en el TOC
"""

from org.gvsig.fmap.mapcontext.events.listeners import ViewPortListener


from libs.formpanel import ProgressBarWithTaskStatus, FormPanel 

class MonitorSuma(ViewPortListener,FormPanel):

  def __init__(self, mapContext, layer, label, fieldname):
    FormPanel.__init__(self,script.getResource("monitor_suma3.xml"))
    
    self.mapContext = mapContext
    self.layer = layer
    self.fieldname = fieldname
    self.lblEtiqueta.setText(label)
    self.calcular_sumatorio()
    mapContext.getViewPort().addViewPortListener(self)

  def btnCerrar_click(self,*args):
    self.mapContext.getViewPort().removeViewPortListener(self)
    self.hide()
    
  def backColorChanged(self,*args):
    pass

  def extentChanged(self,*args):
    self.calcular_sumatorio()

  def projectionChanged(self,*args):
    pass

  def calcular_sumatorio(self):
    encuadre = self.mapContext.getViewPort().getEnvelope().getGeometry()
    lineas = self.layer.getFeatureStore().getFeatureSet().iterator()
    suma = 0
    for linea in lineas:
      g = linea.getDefaultGeometry()
      if encuadre.intersects(g) :
        suma += int(linea.get(self.fieldname))
    self.txtSuma.setText(str(suma))

def main(*args):
  if currentView() == None:
    msgbox("Debera tener una vista abierta y activa")
    return
  mapContext = currentView().getMapContext()
 
  layer = currentLayer()
  if layer == None:
    msgbox("Debera tener seleccionada la capa sobre la que desea trabajar")
    return
  fieldname = inputbox(
    "Introduzca el nombre del campo para calcular el sumatorio",
    "Nombre de campo",
    QUESTION,
    "pob_total"
  )
  if fieldname in ("",None):
    msgbox("Operacion cancelada")
    return
  label = inputbox("Introduzca una etiqueta para el sumatorio de '%s':" % fieldname,
    "Etiqueta",
    QUESTION,
    fieldname
  )
  monitor = MonitorSuma(mapContext, layer, label, fieldname)
  monitor.showTool("monitor")
