# -*- coding: utf-8 -*-
#-----------------------------------------------------------
#
# fTools
# Copyright (C) 2008-2011  Carson Farmer
# EMAIL: carson.farmer (at) gmail.com
# WEB  : http://www.ftools.ca/fTools.html
#
# A collection of data management and analysis tools for vector data
#
#-----------------------------------------------------------
#
# licensed under the terms of GNU GPL 2
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#---------------------------------------------------------------------

from PyQt4.QtCore import QObject, SIGNAL, QFile, QThread, QSettings, QVariant
from PyQt4.QtGui import QDialog, QDialogButtonBox, QMessageBox
from qgis.core import QGis, QgsVectorFileWriter, QgsFeature, QgsGeometry, QgsCoordinateTransform, QgsFields, QgsField, QgsFeatureRequest, QgsPoint, QgsDistanceArea
from ui_frmGeometry import Ui_Dialog
import ftools_utils
import voronoi
from sets import Set

class GeometryDialog( QDialog, Ui_Dialog ):
  def __init__( self, iface, function ):
    QDialog.__init__( self, iface.mainWindow() )
    self.iface = iface
    self.setupUi( self )
    self.myFunction = function
    self.buttonOk = self.buttonBox_2.button( QDialogButtonBox.Ok )
    QObject.connect( self.toolOut, SIGNAL( "clicked()" ), self.outFile )
    if self.myFunction == 1:
      QObject.connect( self.inShape, SIGNAL( "currentIndexChanged( QString )" ), self.update )
    elif self.myFunction == 5:
      QObject.connect( self.chkWriteShapefile, SIGNAL( "stateChanged( int )" ), self.updateGui )
      self.updateGui()
    self.manageGui()
    self.success = False
    self.cancel_close = self.buttonBox_2.button( QDialogButtonBox.Close )
    self.progressBar.setValue( 0 )

  def update( self ):
    self.cmbField.clear()
    inputLayer = unicode( self.inShape.currentText() )
    if inputLayer != "":
      changedLayer = ftools_utils.getVectorLayerByName( inputLayer )
      changedField = ftools_utils.getFieldList( changedLayer )
      for f in changedField:
        self.cmbField.addItem( unicode( f.name() ) )
      self.cmbField.addItem( "--- " + self.tr( "Merge all" ) + " ---" )

  def accept( self ):
    if self.inShape.currentText() == "":
      QMessageBox.information( self, self.tr( "Geometry" ),
                               self.tr( "Please specify input vector layer" ) )
    elif self.outShape.text() == "" and self.myFunction != 5:
      QMessageBox.information( self, self.tr( "Geometry" ),
                               self.tr( "Please specify output shapefile" ) )
    elif self.lineEdit.isVisible() and self.lineEdit.value() < 0.00:
      QMessageBox.information( self, self.tr( "Geometry" ),
                               self.tr( "Please specify valid tolerance value" ) )
    elif self.cmbField.isVisible() and self.cmbField.currentText() == "":
      QMessageBox.information( self, self.tr( "Geometry" ),
                               self.tr( "Please specify valid UID field" ) )
    else:
      self.outShape.clear()
      self.geometry( self.inShape.currentText(), self.lineEdit.value(),
                     self.cmbField.currentText() )

  def outFile( self ):
    self.outShape.clear()
    (self.shapefileName, self.encoding) = ftools_utils.saveDialog( self )
    if self.shapefileName is None or self.encoding is None:
      return
    self.outShape.setText( self.shapefileName )

  def manageGui( self ):
    self.lblField.setVisible( False )
    self.cmbField.setVisible( False )

    self.lblCalcType.setVisible( False )
    self.cmbCalcType.setVisible( False )

    self.chkUseSelection.setVisible( False )
    self.chkByFeatures.setVisible( False )

    self.chkWriteShapefile.setVisible( False )
    if self.myFunction == 1: # Singleparts to multipart
      self.setWindowTitle( self.tr( "Singleparts to multipart" ) )
      self.lineEdit.setVisible( False )
      self.label.setVisible( False )
      self.lblOutputShapefile.setText( self.tr( "Output shapefile" ) )
      self.cmbField.setVisible( True )
      self.lblField.setVisible( True )
    elif self.myFunction == 2: # Multipart to singleparts
      self.setWindowTitle( self.tr( "Multipart to singleparts" ) )
      self.lineEdit.setVisible( False )
      self.label.setVisible( False )
      self.lblOutputShapefile.setText( self.tr( "Output shapefile" ) )
    elif self.myFunction == 3: # Extract nodes
      self.setWindowTitle( self.tr( "Extract nodes" ) )
      self.lineEdit.setVis
ible( False )
      self.label.setVisible( False )
    elif self.myFunction == 4: # Polygons to lines
      self.setWindowTitle( self.tr(  "Polygons to lines" ) )
      self.lblOutputShapefile.setText( self.tr( "Output shapefile" ) )
      self.label_3.setText( self.tr( "Input polygon vector layer" ) )
      self.label.setVisible( False )
      self.lineEdit.setVisible( False )
    elif self.myFunction == 
5: # Export/Add geometry columns
      self.setWindowTitle( self.tr(  "Export/Add geometry columns" ) )
      self.lblOutputShapefile.setText( self.tr( "Output shapefile" ) )
      self.label_3.setText( self.tr( "Input vector layer" ) )
      self.label.setVisible( False )
      self.lineEdit.setVisible( False )
      # populate calculation types
      self.lblCalcType.setVisible( True )
      self.cmbCalcType.setVisible( True )
      self.cmbCalcType.addItem( self.tr( "Layer CRS" ) )
      self.cmbCalcType.addItem( self.tr( "Project CRS" ) )
      self.cmbCalcType.addItem( self.tr( "Ellipsoid" ) )

      self.chkWriteShapefile.setVisible( True )
      self.chkWriteShapefile.setChecked( False )
      self.lblOutputShapefile.setVisible( False )
    elif self.myFunction == 7: # Polygon centroids
      self.setWindowTitle( self.tr( "Polygon centroids" ) )
      self.lblOutputShapefile.setText( self.tr( "Output point shapefile" ) )
      self.label_3.setText( self.tr( "Input polygon vector layer" ) )
      self.label.setVisible( False )
      self.lineEdit.setVisible( False )
    else:
      if self.myFunction == 8: # Delaunay triangulation
        self.setWindowTitle( self.tr( "Delaunay triangulation" ) )
        self.label_3.setText( self.tr( "Input point vector layer" ) )
        self.label.setVisible( False )
        self.lineEdit.setVisible( False )
      elif self.myFunction == 10: # Voronoi Polygons
        self.setWindowTitle( self.tr( "Voronoi polygon" ) )
        self.label_3.setText( self.tr( "Input point vector layer" ) )
        self.label.setText( self.tr( "Buffer region" ) )
        self.lineEdit.setSuffix( " %" )
        self.lineEdit.setRange( 0, 100 )
        self.lineEdit.setSingleStep( 5 )
        self.lineEdit.setValue( 0 )
      elif self.myFunction == 11:  # Lines to polygons
        self.setWindowTitle( self.tr(  "Lines to polygons" ) )
        self.lblOutputShapefile.setText( self.tr( "Output shapefile" ) )
        self.label_3.setText( self.tr( "Input line vector layer" ) )
        self.label.setVisible( False )
        self.lineEdit.setVisible( False )
      else: # Polygon from layer extent
        self.setWindowTitle( self.tr( "Polygon from layer extent" ) )
        self.label_3.setText( self.tr( "Input layer" ) )
        self.label.setVisible( False )
        self.lineEdit.setVisible( False )
        self.chkByFeatures.setVisible( True )
        self.chkUseSelection.setVisible( True )
      self.lblOutputShapefile.setText( self.tr( "Output polygon shapefile" ) )
    self.resize( 381, 100 )
    self.populateLayers()

  def updateGui( self ):
    if self.chkWriteShapefile.isChecked():
      self.lineEdit.setEnabled( True )
