# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtXml
from qgis.core import *
from qgis.gui import *
import os, time, math
from helmert2d.tools.doTransformationStatistics import TransformationStatistics
import helmert2d.tools.utils


class ExportTransformationParameters( QObject ):
    
    def __init__(self):

        self.settings = QSettings("CatAIS","helmert2d")
        self.outputdir = self.settings.value("outputdir")

    
    def run( self, iface, transformationParameters, transformedSimplePoints, inputGlobalLayerName, inputLocalLayerName, transformationType, estimateScale, estimateRotation, version ):
        
        if self.outputdir == None:
            QMessageBox.warning( None, "helmert2d", "No output directory set.")
            return

        time = QDateTime.currentDateTime()
        fileSuffix = str(time.toString(Qt.ISODate)).replace(":", "").replace("-", "")
        filePath = os.path.join(str(self.outputdir.toString()), str("helmert2d_transformation_parameters") + str("_") + fileSuffix + str(".txt"))
        
        print filePath

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            fh = open(filePath, "w")
            s = "Helmert2d-Plugin for QGIS / Version: " + str(version) + "\n"
            fh.write(s.upper())
            fh.write("==========================================\n\n")
            
            
            s = str(QCoreApplication.translate("Helmert2dExport", "Input data"))
            fh.write(s.upper())
            fh.write("\n")     

            s = str(QCoreApplication.translate("Helmert2dExport", "----------")) 
            fh.write(s)    
            fh.write("\n")     
            fh.write("\n")     
            
            
            s = str("%-18s") % str(QCoreApplication.translate("Helmert2dExport", "Date"))
            fh.write(s)
            
            s = str("%-4s") % ":"
            fh.write(s)
            
            s = str("%-50s") % str(time.toString("d. MMMM yyyy hh:mm:ss"))
            fh.write(s)
            fh.write("\n")
            fh.write("\n")

            s = str("%-18s") % str(QCoreApplication.translate("Helmert2dExport", "Global layer"))
            fh.write(s)
            
            s = str("%-4s") % ":"
            fh.write(s)          
          
            s = str("%-50s") % inputGlobalLayerName
            fh.write(s)    
            fh.write("\n")
            
            s = str("%-18s") % str(QCoreApplication.translate("Helmert2dExport", "Local layer"))
            fh.write(s)
            
            s = str("%-4s") % ":"
            fh.write(s)          
          
            s = str("%-50s") % inputLocalLayerName
            fh.write(s)    
            fh.write("\n")
            fh.write("\n")
            
            s = str("%-18s") % str(QCoreApplication.translate("Helmert2dExport", "Map crs"))
            fh.write(s)
            
            s = str("%-4s") % ":"
            fh.write(s)          
          
            srsDescription = iface.mapCanvas().mapRenderer().destinationCrs().description() 
            srsAuthId = iface.mapCanvas().mapRenderer().destinationCrs().authid()    
            srs = str(srsDescription) + str( " (") + str(srsAuthId) + str(")")
            s = str("%-50s") % srs
            fh.write(s)    
            fh.write("\n")
        
            globalLayer = helmert2d.tools.utils.getVectorLayerByName(inputGlobalLayerName)
            localLayer = helmert2d.tools.utils.getVectorLayerByName(inputLocalLayerName)
                
            if globalLayer != None and localLayer != None:

                srsGlobalLayerAuthId = globalLayer.crs().authid()
                srsGlobalLayerDescription = globalLayer.crs().description()
                srsGlobalLayer = str(srsGlobalLayerDescription) + str( " (") + str(srsGlobalLayerAuthId) + str(")")
                
                srsLocalLayerAuthId = localLayer.crs().authid()
                srsLocalLayerDescription = localLayer.crs().description()                
                srsLocalLayer = str(srsLocalLayerDescription) + str( " (") + str(srsLocalLayerAuthId) + str(")")            
            
                s = str("%-18s") % str(QCoreApplication.translate("Helmert2dExport", "Global layer crs"))
                fh.write(s)
                s = str("%-4s") % ":"
                fh.write(s)          
                s = str("%-50s") % srsGlobalLayer
                fh.write(s)    
                fh.write("\n")
                
                s = str("%-18s") % str(QCoreApplication.translate("Helmert2dExport", "Local layer crs"))
                fh.write(s)
                s = str("%-4s") % ":"
                fh.write(s)          
                s = str("%-50s") % srsLocalLayer
                fh.write(s)    
                fh.write("\n")                

            fh.write("\n")
            fh.write("\n")
        

            s =  str(QCoreApplication.translate("Helmert2dExport", "Transformation parameters")) 
            fh.write(s.upper())    
            fh.write("\n")
            
            s = str(QCoreApplication.translate("Helmert2dExport", "--------------------------")) 
            fh.write(s)    
            fh.write("\n")     
            fh.write("\n")                 
                        
            a = transformationParameters[0]
            b = transformationParameters[1] 
            c = transformationParameters[2] 
            d = transformationParameters[3] 
                        
            tx = QString.number(float(a), 'f', 6)
            ty = QString.number(float(b), 'f', 6)

#            m = (float(c)**2 + float(d)**2 )**0.5            
#            ppm = (1 - m) * 1000000
#            rot = math.degrees(math.acos ( float(c)/m ))  / 0.9
            
            rot = math.degrees(math.atan(float(d)/float(c))) / 0.9
            m = float(c) / math.cos(rot)
            ppm = (1 - m) * 1000000

            ppmString = QString.number(float(ppm), 'f', 1)
            rotString = QString.number(float(rot), 'f', 6)            
            
            transformationStatistic = TransformationStatistics(transformedSimplePoints, transformationType, estimateScale, estimateRotation)
            m0 = transformationStatistic.getDeviationOfResidual()
            mpnt = transformationStatistic.getDeviationOfPoint()
            numGcp = transformationStatistic.getNumberOfGcp()
            numParams = transformationStatistic.getNumberOfParameters()
            
            s = str("%-10s") % ""
            fh.write(s)        
        
            s = str("%-25s") % str(QCoreApplication.translate("Helmert2dExport", "Number of parameters"))
            fh.write(s)    

            s = str("%-4s") % ":"
            fh.write(s)          

            s = str("%-4s") % numParams
            fh.write(s)          
            fh.write("\n")
            fh.write("\n")

            if transformationType == 1:
            
                s = str("%-10s") % ""
                fh.write(s)
                s = str("%-25s") % str(QCoreApplication.translate("Helmert2dExport", "X0 [m]"))
                fh.write(s)    
                s = str("%-4s") % ":"
                fh.write(s)          
                s = str("%-10s") % tx
                fh.write(s)          
                fh.write("\n")

                s = str("%-10s") % ""
                fh.write(s)
                s = str("%-25s") % str(QCoreApplication.translate("Helmert2dExport", "Y0 [m]"))
                fh.write(s)    
                s = str("%-4s") % ":"
                fh.write(s)          
                s = str("%-10s") % ty
                fh.write(s)                       
                fh.write("\n")

                s = str("%-10s") % ""
                fh.write(s)
                s = str("%-25s") % str(QCoreApplication.translate("Helmert2dExport", "Drehung [gon]"))
                fh.write(s)    
                s = str("%-4s") % ":"
                fh.write(s)          
                s = str("%-10s") % rotString
                fh.write(s)    
                fh.write("\n")

                s = str("%-10s") % ""
                fh.write(s)
                s = str("%-25s") % str(QCoreApplication.translate("Helmert2dExport", "Massstab [mm/km]"))
                fh.write(s)    
                s = str("%-4s") % ":"
                fh.write(s)          
                s = str("%-10s") % ppmString
                fh.write(s)                    
                fh.write("\n")
                fh.write("\n")

            s = str("%-40s") % str(QCoreApplication.translate("Helmert2dExport", "Standard deviation of residual [mm]"))
            fh.write(s)    
            s = str("%-4s") % ":"
            fh.write(s)          
            s = str("%-10s") % QString.number(float(m0), 'f', 1)
            fh.write(s)                    
            fh.write("\n")
            
            s = str("%-40s") % str(QCoreApplication.translate("Helmert2dExport", "Standard deviation of a point [mm]"))
            fh.write(s)    
            s = str("%-4s") % ":"
            fh.write(s)          
            s = str("%-10s") % QString.number(float(mpnt), 'f', 1)
            fh.write(s)                    
            fh.write("\n")      
            fh.write("\n")      

            s = str("%-40s") % str(QCoreApplication.translate("Helmert2dExport", "Number of control points"))
            fh.write(s)    
            s = str("%-4s") % ":"
            fh.write(s)          
            s = str("%-10s") % numGcp
            fh.write(s)                    
            fh.write("\n")      

            redundancy = 2*numGcp - numParams
            s = str("%-40s") % str(QCoreApplication.translate("Helmert2dExport", "Redundancy"))
            fh.write(s)    
            s = str("%-4s") % ":"
            fh.write(s)          
            s = str("%-10s") % redundancy
            fh.write(s)                    
            fh.write("\n")     
            fh.write("\n")     
            fh.write("\n")     

            s = str(QCoreApplication.translate("Helmert2dExport", "Transformation"))
            fh.write(s.upper())
            fh.write("\n")     

            s = str(QCoreApplication.translate("Helmert2dExport", "--------------")) 
            fh.write(s)    
            fh.write("\n")     
            fh.write("\n")     

            s = str(QCoreApplication.translate("Helmert2dExport", "Control points and residuals"))
            fh.write(s.upper())
            fh.write("\n")     

            s = str(QCoreApplication.translate("Helmert2dExport", "-----------------------------")) 
            fh.write(s)    
            fh.write("\n")     
            fh.write("\n")     
            
            s = str("%-15s") % str(QCoreApplication.translate("Helmert2dExport", "Point ident"))
            fh.write(s)    
            
            s = str("%-3s") % str(QCoreApplication.translate("Helmert2dExport", "gcp"))
            fh.write(s)                
            
            s = str("%14s") % str(QCoreApplication.translate("Helmert2dExport", "x local"))
            fh.write(s)  

            s = str("%14s") % str(QCoreApplication.translate("Helmert2dExport", "y local"))
            fh.write(s)  
            
            s = str("%17s") % str(QCoreApplication.translate("Helmert2dExport", "x global"))
            fh.write(s)  
            
            s = str("%14s") % str(QCoreApplication.translate("Helmert2dExport", "y global"))
            fh.write(s)              

            s = str("%10s") % str(QCoreApplication.translate("Helmert2dExport", "res x"))
            fh.write(s)    
            
            s = str("%10s") % str(QCoreApplication.translate("Helmert2dExport", "res y"))
            fh.write(s)                

            fh.write("\n")     
            fh.write("\n")     

            for point in transformedSimplePoints:
                pnt = point.getIdent()
                
                gcp = str(QCoreApplication.translate("Helmert2dExport", "no")) 
                if point.isChecked() == True:
                    gcp = str(QCoreApplication.translate("Helmert2dExport", "yes"))
                
                xlocal = point.getXlocal()
                ylocal = point.getYlocal()
                
                xglobal = point.getXglobal()
                yglobal = point.getYglobal()              
              
                xtrans = point.getXtrans()
                ytrans = point.getYtrans()                  
            
                s = str("%-15s") % pnt
                fh.write(s)
                
                s = str("%-3s") % gcp
                fh.write(s)                
                
                s = str("%14s") % QString.number(float(xlocal), 'f', 3)
                fh.write(s)

                s = str("%14s") % QString.number(float(ylocal), 'f', 3)
                fh.write(s)

                s = str("%17s") % QString.number(float(xglobal), 'f', 3)
                fh.write(s)
                
                s = str("%14s") % QString.number(float(yglobal), 'f', 3)
                fh.write(s)                
                
                vx = (float(xtrans) - float(xglobal)) * 1000
                vy = (float(ytrans) - float(yglobal)) * 1000

                s = str("%10s") % QString.number(float(vx), 'f', 1)
                fh.write(s)                

                s = str("%10s") % QString.number(float(vy), 'f', 1)
                fh.write(s)       
                
                fh.write("\n")
                
            fh.close()

        except IOError:
#        except IOError as detail:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning( None, "Helmert2d", "Cannot open file.")
            print "Helmert2d: IOError Exception."
#            print str(detail)

        else:
            fh.close()
            QApplication.restoreOverrideCursor()

