# -*- 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
#
# Geoprocessing functions adapted from 'Geoprocessing Plugin',
# (C) 2008 by Dr. Horst Duester, Stefan Ziegler
#-----------------------------------------------------------
#
# 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 *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from ui_frmGeoprocessing import Ui_Dialog
import ftools_utils
import sys

class GeoprocessingDialog( QDialog, Ui_Dialog ):
  def __init__( self, iface, function ):
    QDialog.__init__( self, iface.mainWindow() )
    self.iface = iface
    self.setupUi( self )
    self.param.setValidator(QDoubleValidator(self.param))
    self.myFunction = function
    QObject.connect( self.btnBrowse, SIGNAL( "clicked()" ), self.outFile )
    QObject.connect( self.inShapeA, SIGNAL( "currentIndexChanged(QString)" ), self.checkA )
    QObject.connect( self.inShapeB, SIGNAL( "currentIndexChanged(QString)" ), self.checkB )
    if function == 4 or function == 1 or function == 2:
      QObject.connect( self.inShapeA, SIGNAL( "currentIndexChanged(QString)" ), self.update )
    self.manageGui()
    self.success = False
    self.cancel_close = self.buttonBox_2.button( QDialogButtonBox.Close )
    self.buttonOk = self.buttonBox_2.button( QDialogButtonBox.Ok )
    self.progressBar.setValue (0 )

  def checkA( self ):
    inputLayer = unicode( self.inShapeA.currentText() )
    if inputLayer != "":
      changedLayer = ftools_utils.getVectorLayerByName( inputLayer )
      if changedLayer.selectedFeatureCount() != 0:
        self.useSelectedA.setCheckState( Qt.Checked )
      else:
        self.useSelectedA.setCheckState( Qt.Unchecked )

  def checkB( self ):
    inputLayer = unicode( self.inShapeB.currentText() )
    if inputLayer != "":
      changedLayer = ftools_utils.getVectorLayerByName( inputLayer )
      if changedLayer.selectedFeatureCount() != 0:
        self.useSelectedB.setCheckState( Qt.Checked )
      else:
        self.useSelectedB.setCheckState( Qt.Unchecked )

  def update( self ):
    self.attrib.clear()
    inputLayer = unicode( self.inShapeA.currentText() )
    if inputLayer != "":
      changedLayer = ftools_utils.getVectorLayerByName( inputLayer )
      changedField = changedLayer.dataProvider().fields()
      for i in changedField:
        self.attrib.addItem( unicode( changedField[i].name() ) )
      if self.myFunction == 4:
        self.attrib.addItem( "--- " + self.tr( "Dissolve all" ) + " ---" )

  def accept( self ):
    if self.inShapeA.currentText() == "":
      QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Please specify an input layer" ) )
    elif self.inShapeB.isVisible() and self.inShapeB.currentText() == "":
      QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Please specify a difference/intersect/union layer" ) )
    elif self.param.isEnabled() and self.param.isVisible() and self.param.text() == "":
      QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Please specify valid buffer value" ) )
    elif self.attrib.isEnabled() and self.attrib.isVisible() and self.attrib.currentText() == "":
      QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Please specify dissolve field" ) )
    elif self.outShape.text() == "":
      QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Please specify output shapefile" ) )
    else:
      changedLayerA = ftools_utils.getVectorLayerByName( self.inShapeA.currentText() )
      changedLayerB = ftools_utils.getVectorLayerByName( self.inShapeB.currentText() )
      # check for selection in layer A
      if self.useSelectedA.isChecked() and changedLayerA.selectedFeatureCount() == 0:
        QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "No features selected, please uncheck 'Use selected' or make a selection" ) )
      # check for selection in layer B
      elif self.inShapeB.isVisible() and self.useSelectedB.isChecked() and changedLayerB.selectedFeatureCount() == 0:
        QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "No features selected, please uncheck 'Use selected' or make a selection" ) )
      else:
        self.outShape.clear()
        if self.attrib.isEnabled():
          self.geoprocessing( self.inShapeA.currentText(), self.inShapeB.currentText(),
          unicode( self.attrib.currentText() ), self.mergeOutput.checkState(), self.useSelectedA.checkState(),
          self.useSelectedB.checkState(), self.spnSegments.value() )
        else:
          if self.param.isEnabled() and self.param.isVisible():
            parameter = float( self.param.text() )
          else:
            parameter = None
          self.geoprocessing( self.inShapeA.currentText(), self.inShapeB.currentText(),
          parameter, self.mergeOutput.checkState(), self.useSelectedA.checkState(), self.useSelectedB.checkState(), self.spnSegments.value() )

  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( QString( self.shapefileName ) )

  def manageGui( self ):
    if self.myFunction == 1:  # Buffer
      self.label_2.hide()
      self.inShapeB.hide()
      self.useSelectedB.hide()
      self.label_4.hide()
      self.setWindowTitle( self.tr( "Buffer(s)" ) )
    elif self.myFunction == 2: # Convex hull
      self.label_2.hide()
      self.inShapeB.hide()
      self.useSelectedB.hide()
      self.rdoBuffer.setText( self.tr( "Create single minimum convex hull" ) )
      self.rdoField.setText( self.tr( "Create convex hulls based on input field" ) )
      self.label_4.hide()
      self.param.hide()
      self.lblSegments.hide()
      self.spnSegments.hide()
      self.setWindowTitle( self.tr( "Convex hull(s)" ) )
      self.mergeOutput.hide()
    elif self.myFunction == 4: # Dissolve
      self.label_2.hide()
      self.inShapeB.hide()
      self.useSelectedB.hide()
      self.rdoBuffer.hide()
      self.attrib.setEnabled( True )
      self.param.hide()
      self.rdoField.hide()
      self.mergeOutput.hide()
      self.lblSegments.hide()
      self.spnSegments.hide()
      self.setWindowTitle( self.tr( "Dissolve" ) )
    else:
      self.rdoBuffer.hide()
      self.param.hide()
      self.label_4.hide()
      self.rdoField.hide()
      self.attrib.hide()
      self.mergeOutput.hide()
      self.lblSegments.hide()
      self.spnSegments.hide()
      if self.myFunction == 3: # Difference
        self.label_2.setText( self.tr( "Difference layer" ) )
        self.setWindowTitle( self.tr( "Difference" ) )
      elif self.myFunction == 5: # Intersect
        self.label_2.setText( self.tr( "Intersect layer" ) )
        self.setWindowTitle( self.tr( "Intersect" ) )
      elif self.myFunction == 7: # Symetrical difference
        self.label_2.setText( self.tr( "Difference layer" ) )
        self.setWindowTitle( self.tr( "Symetrical difference" ) )
        self.useSelectedA.hide()
        self.useSelectedB.hide()
      elif self.myFunction == 8: # Clip
        self.label_2.setText( self.tr( "Clip la