"""
/***************************************************************************
 FlowMapper
                                 A QGIS plugin
 This plugin generates discreet flow lines between nodes
                              -------------------
        begin                : 2011-12-04
        copyright            : (C) 2011 by Cem GULLUOGLU
        email                : cempro@gmail.com
 ***************************************************************************/
"""

import sys
import os
#from os.path import isfile
from os.path import realpath
from os.path import isfile

import qgis.gui
from PyQt4 import QtCore, QtGui

#import ogr
from osgeo import ogr

# Import the PyQt and QGIS libraries
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *

from qgis.gui import *

# Initialize Qt resources from file resources.py
import resources

# Import the code for the dialog
from flowmapperdialog import FlowMapperDialog
import flowmapperdialog

from form2dialog import Form2Dialog
import form2dialog

import form_aboutdialog

# Import script that draws flow lines (kullan)
import flowpyv07
#import flowpyInterface (iptal)

class FlowMapper:
  
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

    def initGui(self):
        # Create action that will start plugin configuration
        self.action = QAction(QIcon(":/plugins/flowmapper/icon.png"), "Flow Mapper", self.iface.mainWindow())
        self.actionform2 = QAction(QIcon(":/plugins/flowmapper/icon2.png"), "Filtering", self.iface.mainWindow())
        self.actionabout = QAction(QIcon(":/plugins/flowmapper/icon3.png"), "About", self.iface.mainWindow())
        
		# connect the action to the run method
        QObject.connect(self.action, SIGNAL("triggered()"), self.run)
        QObject.connect(self.actionform2, SIGNAL("triggered()"), self.form2)
        QObject.connect(self.actionabout, SIGNAL("triggered()"), self.about)
        
        # Add toolbar button and menu item to QGIS
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu("&Flow Mapper", self.action)
        self.iface.addPluginToMenu("&Flow Mapper", self.actionform2)
        self.iface.addPluginToMenu("&Flow Mapper", self.actionabout)
       
       
       
    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu("&Flow Mapper",self.action)
        self.iface.removeToolBarIcon(self.action)
        
        self.iface.removePluginMenu("&Flow Mapper", self.actionform2)
        self.iface.removeToolBarIcon(self.actionform2)
        
        self.iface.removePluginMenu("&Flow Mapper", self.actionabout)
        self.iface.removeToolBarIcon(self.actionabout)

    def OutputShp(self):

        dlg = FlowMapperDialog()

        #buttona basip file browser ile output shapefile dosya adi vermek icin fonksiyon
        fd = QtGui.QFileDialog(dlg)
        global SaveShpName
        global SaveShpDirectory
        SaveShpName = fd.getSaveFileName(None, 'Shapefile(*.shp)', 'Type output shapefile name', '*.shp')
        #SaveShpDirectory = os.path.realpath(


		
    def InputNodes(self):

        dlg = FlowMapperDialog()

        #buttona basip file browser ile input node coord. txt dosyasini sectirmek icin fonksiyon
        fd = QtGui.QFileDialog(dlg)
        global InputNodesName
        InputNodesName = fd.getOpenFileName(None, 'Text Files(*.txt)', 'Select txt file', '*.txt')

        
    def InputMatrix(self):

        dlg = FlowMapperDialog()

        #buttona basip file browser ile flow matrix txt dosyasini sectirmek icin fonksiyon
        fd = QtGui.QFileDialog(dlg)
        global InputMatrixName
        InputMatrixName = fd.getOpenFileName(None, 'Text Files(*.txt)', 'Select txt file', '*.txt')

    def InputShpFilter(self):
        
        dlg = Form2Dialog()

        fd = QtGui.QFileDialog(dlg)
        global InputShpFilterName
        global InputShpFilterDirectory
        InputShpFilterName = fd.getOpenFileName(None, 'Shapefile(*.shp)', 'Select shapefile for filtering', '*.shp')
        
        InputShpFilterDirectory = os.path.realpath(InputShpFilterName)


        
                
    def OutputShpFilter(self):

        dlg = Form2Dialog()

        fd = QtGui.QFileDialog(dlg)
        global OutputShpFilterName
        global OutputShpFilterDirectory
        OutputShpFilterName = fd.getSaveFileName(None, 'Shapefile(*.shp)', 'Type output shapefile name (filtered)', '*.shp')
        
        OutputShpFilterDirectory = os.path.realpath(OutputShpFilterName)
        
    def CalStatFilter(self):
    
        global CalStatNoOfFeatures
        global CalStatNoOfFeaturesNotZero
        global CalStatSumMagnitude
        global CalStatMaxFlow
        global CalStatMinFlow
        global CalStatMean
        global CalStatMeanNotZero        
        global CalStatStdDev
        global CalStatStdDevNotZero
        
        shp = ogr.Open(InputShpFilterDirectory,1)
        layer = shp.GetLayer(0)
        #get number of all features in shapefile
        CalStatNoOfFeatures = str(layer.GetFeatureCount())
        
#----------------------------------------------------------------------------------------------------        
        feature = layer.GetNextFeature()
        counterNotZero = 0
        CalStatSumMagnitude = 0
        while feature:
            magnitude = feature.GetField('magnitude')
            if magnitude > 0:
                counterNotZero = counterNotZero + 1
            CalStatSumMagnitude = CalStatSumMagnitude + magnitude
            feature.Destroy()
            feature = layer.GetNextFeature()
        CalStatMean = str((CalStatSumMagnitude / int(CalStatNoOfFeatures)))
        CalStatMean = str(round(float(CalStatMean), 3))
        CalStatMeanNotZero = str(CalStatSumMagnitude / int(counterNotZero))
        CalStatMeanNotZero = str(round(float(CalStatMeanNotZero), 3))
        
        CalStatSumMagnitude = str(CalStatSumMagnitude)
        CalStatNoOfFeaturesNotZero = str(int(CalStatNoOfFeatures)-int(counterNotZero))
        
        layer.ResetReading()
        
        feature = layer.GetNextFeature()
        var = 0
        varNotZero = 0
        CalStatMaxFlow = 0
        CalStatMinFlow = 0        
        while feature:
            magnitude = feature.GetField('magnitude')
            if magnitude >= CalStatMaxFlow:
                CalStatMaxFlow = magnitude
            var = var + ((magnitude - float(CalStatMean))**2)
            if magnitude > 0:
                varNotZero = varNotZero + ((magnitude - float(CalStatMeanNotZero))**2)
            feature.Destroy()
            feature = layer.GetNextFeature()
        CalStatStdDev = str((var / int(CalStatNoOfFeatures))**0.5)
        CalStatStdDev = str(round(float(CalStatStdDev), 3))
        CalStatStdDevNotZero = str((varNotZero / int(counterNotZero))**0.5)
        CalStatStdDevNotZero = str(round(float(CalStatStdDevNotZero), 3))
        
        CalStatMaxFlow = str(int(CalStatMaxFlow))
        
        layer.ResetReading()
        
        feature = layer.GetNextFeature()
        
        shp.Destroy()

#----------------------------------------------------------------------------------------------------
        QMessageBox.information(self.iface.mainWindow(),"info" ,QString("Statistics calculated successfully !"))
        #QMessageBox.information(self.iface.mainWindow(),"minflow" ,QString(str(CalStatMinFlow)))   
        #QMessageBox.information(self.iface.mainWindow(),"maxflow" ,QString(str(CalStatMaxFlow)))   
        #QMessageBox.information(self.iface.mainWindow(),"info" ,QString(str(CalStatSumMagnitude)))   
        #QMessageBox.information(self.iface.mainWindow(),"info" ,QString(str(CalStatStdDevNotZero)))               
        #QMessageBox.information(self.iface.mainWindow(),"info" ,QString(str(CalStatStdDev)))               
        #QMessageBox.information(self.iface.mainWindow(),"info" ,QString(str(CalStatMeanNotZero)))               
        #QMessageBox.information(self.iface.mainWindow(),"info" ,QString(str(CalStatMean)))   
        


    def Filter(self):
        dlg = Form2Dialog() 
        
        text = dlg.ui.Filter_LineEdit.text()
                
        QMessageBox.information(self.iface.mainWindow(),"cmd" , QString(InputShpFilterName))
    
        #QMessageBox.about(self.iface.mainWindow(), "My message box", "Text1 = %s" % (dlg.ui.Filter_LineEdit.text()))
        
                
        #dlg.show()
        #dlg.exec_()
        command =  "\"ogr2ogr -f \'ESRI Shapefile\' -where \'magnitude > ", Threshold, "'", OutputShpFilterDirectory, InputShpFilterDirectory, "\""
        QMessageBox.information(self.iface.mainWindow(),"cmd" ,QString(str(command)))
        os.system(str(command))

        
    
    def form2(self):
        
        dlg = Form2Dialog() 
        #dlg.exec_()
        dlg.show()
        
        dlg.ui.CalStat.setEnabled(False)
        
        global text
        text = dlg.ui.Filter_LineEdit.text()

        
        #result = dlg2.exec_() 
        
        QtCore.QObject.connect(dlg.ui.BrowseShapeInputFilter,QtCore.SIGNAL("clicked()"), self.InputShpFilter)
        QtCore.QObject.connect(dlg.ui.BrowseShapeInputFilter,QtCore.SIGNAL("clicked()"), dlg.SetTextBrowseInputShapeFilter)
        
        QtCore.QObject.connect(dlg.ui.BrowseShapeOutputFilter,QtCore.SIGNAL("clicked()"), self.OutputShpFilter)
        QtCore.QObject.connect(dlg.ui.BrowseShapeOutputFilter,QtCore.SIGNAL("clicked()"), dlg.SetTextBrowseOutputShapeFilter) 

        #get stats
        QtCore.QObject.connect(dlg.ui.CalStat,QtCore.SIGNAL("clicked()"), self.CalStatFilter)
        QtCore.QObject.connect(dlg.ui.CalStat,QtCore.SIGNAL("clicked()"), dlg.No_Of_Features)
        QtCore.QObject.connect(dlg.ui.CalStat,QtCore.SIGNAL("clicked()"), dlg.No_Of_FeaturesNotZero)
        QtCore.QObject.connect(dlg.ui.CalStat,QtCore.SIGNAL("clicked()"), dlg.Mean)
        QtCore.QObject.connect(dlg.ui.CalStat,QtCore.SIGNAL("clicked()"), dlg.MeanNotZero)
        QtCore.QObject.connect(dlg.ui.CalStat,QtCore.SIGNAL("clicked()"), dlg.MaxFlow)
        QtCore.QObject.connect(dlg.ui.CalStat,QtCore.SIGNAL("clicked()"), dlg.SumMagnitude)
        QtCore.QObject.connect(dlg.ui.CalStat,QtCore.SIGNAL("clicked()"), dlg.StdDev)
        QtCore.QObject.connect(dlg.ui.CalStat,QtCore.SIGNAL("clicked()"), dlg.StdDevNotZero)
        
        
        #dlg.exec_()         
        
        #perform filtering when filter button clicked
        #QtCore.QObject.connect(dlg.ui.FilterButton,QtCore.SIGNAL("clicked()"), self.Filter)

        #dlg.exec_() 
        
        #OutputShpFilterDirectory = os.path.realpath(InputShpFilterName)
        
        result = dlg.exec_() 
        # See if OK was pressed

        
        if result == 1:

            text = dlg.ui.Filter_LineEdit.text()
            #QMessageBox.information(self.iface.mainWindow(),"cmd" , QString(text))
            
            command1 = 'ogr2ogr -f "ESRI Shapefile" -where "magnitude > '
            command2 = '"'
            command3 = '\"'
            command = str(command1)+str(text)+ str(command2)+" "+ str(OutputShpFilterName)+ " "+str(InputShpFilterName)
            
            #QMessageBox.information(self.iface.mainWindow(),"info" ,QString(str(command)))
                        
            os.system(command)
            
            self.iface.addVectorLayer(str(OutputShpFilterName), str(OutputShpFilterName), "ogr")
            
            message = "Flows less than "+str(text)+" filtered and "+str(OutputShpFilterName)+" created successfully !"
            QMessageBox.information(self.iface.mainWindow(),"info" ,QString(message))
            
            #dlg.Filter_LineEdit_2.setText(text)

        
            #QMessageBox.information(self.iface.mainWindow(),"in_shp________" ,QString(InputShpFilterName))
            #QMessageBox.information(self.iface.mainWindow(),"out_shp________" ,QString(OutputShpFilterName))
            #QMessageBox.information(self.iface.mainWindow(),"out_dir________" ,QString(OutputShpFilterDirectory))
        
            #QMessageBox.information(self.iface.mainWindow(), "Success!_______", QString('Close'))

       
            
    def about(self):
        dlg = form_aboutdialog.Form_AboutDialog() 
        #dlg.show()
        dlg.exec_() 
        #result = dlg3.exec_() 



        # run method that performs all the real work
    def run(self):
        # create and show the dialog
        dlg = FlowMapperDialog()

        # show the dialog
        dlg.show()

        
        #browse for file penceresini acmak icin SaveShp e signal yollar
        QtCore.QObject.connect(dlg.ui.BrowseShape,QtCore.SIGNAL("clicked()"), self.OutputShp)
        QtCore.QObject.connect(dlg.ui.BrowseShape,QtCore.SIGNAL("clicked()"), dlg.SetTextBrowseShape)

        QtCore.QObject.connect(dlg.ui.BrowseNodes,QtCore.SIGNAL("clicked()"), self.InputNodes)
        QtCore.QObject.connect(dlg.ui.BrowseNodes,QtCore.SIGNAL("clicked()"), dlg.SetTextBrowseNodes)
        
        QtCore.QObject.connect(dlg.ui.BrowseMatrix,QtCore.SIGNAL("clicked()"), self.InputMatrix)
        QtCore.QObject.connect(dlg.ui.BrowseMatrix,QtCore.SIGNAL("clicked()"), dlg.SetTextBrowseMatrix)
        
        
        

		
#	    if len(SaveShpName) < 2:
#       msgbox = QMessageBox()
#       msgbox.setText(SaveShpName)
#       msgbox.exec_()
		
        result = dlg.exec_()
        if result == 1:
            if dlg.ui.TwowayRadioButton.isChecked():
                FlowType = 1
            elif dlg.ui.GrossRadioButton.isChecked():
                FlowType = 2
            elif dlg.ui.NetRadioButton.isChecked():
                FlowType = 3
		
        #FlowType = dlg.ui.spinBoxType.value()

            SaveDirectory = os.path.realpath(SaveShpName)
		
            #flowpyv07.shapefilemaker(FlowType,'C:/Users/cem/.qgis/python/plugins/FlowMapper',str(OutputShpAdi)+'.shp','C:/Users/cem/.qgis/python/plugins/FlowMapper/bankinteract.txt','C:/Users/cem/.qgis/python/plugins/FlowMapper/bankpoints.txt')      

            flowpyv07.shapefilemaker(FlowType,str(SaveDirectory), str(SaveShpName),str(InputMatrixName),str(InputNodesName))
	
#	msgbox = QMessageBox()
#	msgbox.setText((SaveShpName), "created")
#	msgbox.exec_()
            
            self.iface.addVectorLayer(str(SaveShpName), str(SaveShpName), "ogr")
            
            SuccessMessage = str(SaveShpName) + " created successfully !"
            QMessageBox.information(self.iface.mainWindow(), "info", QString(SuccessMessage), QString('Close'))
            
            


	
        #'C:/Users/cem/.qgis/python/plugins/FlowMapper'

	# do something useful (delete the line containing pass and
        # substitute with your code
        #pass
	#execfile("somefile.py")


