#include <ColorConstantS.au3>
#include <Excel.au3>
#include <File.au3>
#include <GUIConstantsEx.au3>
#include <IE.au3>
#include <inet.au3>
#include <OutlookEx.au3>
#include <MsgBoxConstants.au3>
#include <WindowsConstants.au3>

;**********************************************************************************
; Dateien Pfad ApiKey evtl. Ändern                                               ;*
Global $ApiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"                              ;*
; Quelldatei von Winitas CSV                                                     ;*
Global $Quelldatei = "C:\Users\xx2\Documents\\Export\Aufträge.csv"               ;*
; Zieldatei AATour.gpx für ITN Converter                                         ;*
Global $Zieldatei  = "C:\Users\xx2\Desktop\AATour.gpx"                           ;*
; My Drive Connect                                                               ;*
Global $DConnect = "C:\Users\xx2\MyDrive Connect\TomTom MyDrive Connect.exe"     ;*
;**********************************************************************************

; Fenster_Excel() ; Funktion prüfen ob Excel.exe offen ist
If ProcessExists("Excel.exe") Then
MsgBox(0,"ExcelDateien schließen","")
Endif

; Gui für Tourenplanug
#Region
; Ganzer Bildschirm freischalten
;GUICreate($Ersteller, @DesktopWidth, @DesktopHeight, 0, 0,$WS_MAXIMIZEBOX+$WS_MAXIMIZE)
Global $Form1   = GUICreate ("Tourenplanung " ,500 ,300 ,800 ,500)
Global $Button1 = GUICtrlCreateButton("MyDrive Connect laden", 150, 50 ,200,30)
Global $Button2 = GUICtrlCreateButton("Adressen Import", 150, 100 ,200,30)
Global $Button3 = GUICtrlCreateButton("Mail mit Telefonnummern", 150, 150 ,200,30)
Global $Button4 = GUICtrlCreateButton("Ende", 150, 200 ,200, 30)
; Fenster im Vordergrund
;WinSetOnTop($Form1,"",1)
;Farbe Sibergrau
GUISetBkColor($COLOR_Silver)
;GUIStartGroup()
GUISetState()
#EndRegion


While 2
   $nMsg = GUIGetMsg() ; X = Ende
   Switch $nMsg
      Case $GUI_EVENT_CLOSE
		    Exit

      Case  $Button1
			Global $DConnect = "C:\Users\xx2\MyDrive Connect\TomTom MyDrive Connect.exe"
			ShellExecute($DConnect,"-startda","","open",@SW_SHOW) ; My Drive Connect mit Parameter "-startda" starten
			;Global $hWnd = WinGetHandle ("[CLASS: Qt5QWindowIcon]")
			Sleep (5000)
			WinSetState ( "MyDrive Connect" ,    "" ,    @SW_MINIMIZE )

			;If _TomTomConnected() Then ConsoleWrite("... TomTom ist verbunden ..." & @CRLF)
			If _TomTomConnected() Then
			   Global $Meldung = _TomTomConnected()
			   MsgBox (0 , "TomTom ist verbunden", $Meldung)
			Else
			   Global $Meldung = _TomTomConnected()
			   MsgBox (0 , "TomTom ist nicht verbunden", $Meldung)
			Endif

	  Case  $Button2
            ;Quell_vorhanden() ; Funtion ob alte Quelldatei vorhanden
		    ;Mausklick() ; Funktion Mauscklick

			;FileMove ( $Quell , $Ziel ,0)
		    ;FileDelete ($Quell)

			; Excel öffnen
            Global $oExcel = _Excel_Open()
            Global $oWorkBook = _Excel_BookOpen($oExcel, $Quelldatei)

			; Kurz Warten und Excel in den Vordergrund
			sleep (500)
			WinActivate ($oWorkbook , "")

            ;SuchNavi()        ; Funtion My Drive Connect mit Parameter "-startda" starten
			Winitas_Datei()   ; Funktion Winitas Datei bearbeiten
			Lat_Lon()         ; Funktion Lat und Lon berechnen
            AATour()          ; Funtion AATour.gpx einlesen

            Dateien_loeschen() ; alle Daten löschen
            _Excel_BookSaveAs ( $oWorkbook ,    "" ,    $xlHtml ,    True )


		 Case $Button3
			Global $Quelldatei = "C:\Users\xx2\Documents\\Export\Aufträge.csv"
			Global $oExcel = _Excel_Open()
			Global $oWorkBook = _Excel_BookOpen($oExcel, $Quelldatei)
			Global $EMail = "xxxx@gmx.de"

			Global $oOutlook = _OL_Open()
		 If @error <> 0 Then Exit MsgBox(16, "OutlookEX UDF", "Error creating a connection to Outlook. @error = " & @error & ", @extended = " & @extended)

			Global $sMeineMailadresse = $EMail
			Global $sBetreff = "Telefonnummern Kunden Tour " & _NowDate()
			Global $aTermine = __ParseCSV($Quelldatei, ';') ; <== Name der Eingabedatei hier anpassen!

			Global $sBody = "<html><body>"
		 For $i = 1 to UBound($aTermine) - 1
			If $aTermine[$i][0] <> "" Then ; ignoriere leere Zeilen
			   $sBody &= "<P><b><u>" & $aTermine[$i][1] & "</u></b><br>" ; Vorname Name
			   $sBody &= $aTermine[$i][2] & "<br>" ; Straße
			   If StringLen($aTermine[$i][3]) = 4 Then
				  $sBody &= "0" & $aTermine[$i][3] & " " & $aTermine[$i][4] & "<br>" ; PLZ Ort 4 stellig mit 0
			   Else
				  $sBody &= $aTermine[$i][3] & " " & $aTermine[$i][4] & "<br>" ; PLZ Ort 5 stellig
			   Endif
			   If $aTermine[$i][5] <> "" Then $sBody &= "Privat: " & $aTermine[$i][5] & "<br>" ; Telefonnr 1
			   If $aTermine[$i][6] <> "" Then $sBody &= "Firma:  " & $aTermine[$i][6] & "<br>" ; Telefonnr 2
			   If $aTermine[$i][7] <> "" Then $sBody &= "Mobil:  " & $aTermine[$i][7] & "<br>" ; Handy
			EndIf
		 Next
			$sBody &= "</html></body>"

			Global $oItem = _OL_ItemCreate($oOutlook, $olMailItem, "", "", "Subject=" & $sBetreff, "BodyFormat=" & $olFormatHTML, "HTMLBody=" & $sBody)
			If @error <> 0 Then Exit MsgBox(16, "", "Item Create: @error = " & @error & ", @extended = " & @extended)
			_OL_ItemRecipientAdd($oOutlook, $oItem, Default, $olTo, $sMeineMailadresse)
			If @error <> 0 Then Exit MsgBox(16, "", "Recipient Add: @error = " & @error & ", @extended = " & @extended)
			;$oItem.send ; sendet ohne nachfrage
			$oItem.display ; zeigt die Mail And
  Case $Button4
	   Exit
EndSwitch
WEnd





;**************************************************************
; Alle Funtionen                                              *
;**************************************************************

Func _TomTomConnected()
    Local $wbemFlagReturnImmediately = 0x10, $wbemFlagForwardOnly = 0x20
    Local $colItems = "", $strComputer = "."
    Local $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\")
    If Not IsObj($objWMIService) Then Return SetError(1, 0, 0)
    $colItems = $objWMIService.ExecQuery('SELECT * FROM Win32_NetworkAdapter Where Name="TomTom" AND NetConnectionStatus=2', "WQL", _
            $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
    For $objItem In $colItems
        Return $objItem.NetConnectionStatus
    Next
    Return SetError(2, 0, 0)
EndFunc   ;==>_TomTomConnected


;Func SuchNavi() ; Navi anmelden bei TomTom
;   ShellExecute($DConnect,"-startda","","open",@SW_Hide) ; My Drive Connect mit Parameter "-startda" starten
;   MsgBox(64,"Title","Schließe das Tom Tom Navigationsgerät an USB an"&@crlf&"und warte bis es verbunden ist")
   ;ShellExecute($DConnect,"-startda","","open",@SW_SHOW) ; My Drive Connect mit Parameter "-startda" starten
;EndFunc

Func Winitas_Datei()
	; Überflüssige Reihen löschen
	_Excel_RangeDelete ($oWorkBook.ActiveSheet, "A:A")
    _Excel_RangeDelete ($oWorkBook.ActiveSheet, "B:B")
	_Excel_RangeDelete ($oWorkBook.ActiveSheet, "C:C")
	_Excel_RangeDelete ($oWorkBook.ActiveSheet, "F:F")
	_Excel_RangeDelete ($oWorkBook.ActiveSheet, "I:M")


    ; Neue Überschriften
	$oExcel.ActiveSheet.Cells(1, 1)  = "Nummer"
    $oExcel.ActiveSheet.Cells(1, 2)  = "Name"
    $oExcel.ActiveSheet.Cells(1, 3)  = "Straße"
    $oExcel.ActiveSheet.Cells(1, 4)  = "PLZ"
    $oExcel.ActiveSheet.Cells(1, 5)  = "Ort"
    $oExcel.ActiveSheet.Cells(1, 8)  = "Handy"
	$oExcel.ActiveSheet.Cells(1, 9)  = "Lat"
	$oExcel.ActiveSheet.Cells(1, 10) = "Lon"

  ; Prüfen ob PLZ Leer dann Zeile löschen
Global $Zzahl = $oExcel.ActiveSheet.Cells($oExcel.Rows.Count, 2).End(-4162).Row ; -4162 = xlUp
Global $R = 2
For $R = 2 To $Zzahl
  Global $PLZ = _Excel_RangeRead($oWorkbook, Default, "D" &$R)
  If $Plz = 0 Then
	Local $srange = $R &":"& $R
	_Excel_RangeDelete($oWorkbook.ActiveSheet, $sRange, $xlShiftUp)
EndIf
Next
EndFunc


Func Lat_Lon()   ; Funktion Lat und Lon berechnen
  ; Suche letzte Zeile
   Global $Zzahl = $oExcel.ActiveSheet.Cells($oExcel.Rows.Count, 2).End(-4162).Row ; -4162 = xlUp
   Global $R = 2
For $R = 2 To $Zzahl
   Global $Strasse = _Excel_RangeRead($oWorkbook, Default, "C" &$R)

   Global $PLZ = _Excel_RangeRead($oWorkbook, Default, "D" &$R)
   If StringLen ($PLZ) = 4 Then
	  Global $PLZ1 = StringLeft ( StringFormat ( '%09s' , $PLZ ) , 9 )
	  Global $PLZ = StringLeft ( $PLZ1 , 1 )  & StringRight ( $PLZ1 , 4 )
   EndIf

   Global $Ort = _Excel_RangeRead($oWorkbook, Default, "E" &$R)
   Global $Adresse = $Strasse&","&  + $PLZ& " "& + $Ort

   $oExcel.Cells($R, 9 ).NumberFormat = "@"
   $oExcel.Cells($R, 10).NumberFormat = "@"



 ; XML Ausgabe = .xml
 ; Sprache = &countrySet=DEU
;MsgBox (0, "Url " , $Url)
 Global $url = ( "https://api.tomtom.com/search/2/geocode/&"&$Adresse&".xml?key="&$ApiKey&"&countrySet=DEU")
;MsgBox (0, "Url " , $Url)

;Sleep ( 100 )

InetGet($Url ,"Koordinaten.xml") ;  Internet Seite speichern

Global $strXML = FileRead("Koordinaten.xml")
;MsgBox (0, "string " , $strXML)

; Berechnung Lat
   Global $Pos1 = StringInStr($strXML, "<lat>")        ; Position von "<lat>")im großen String   = 1141
;MsgBox (0, "pos1 " , $pos1)
   Global $neuPos1  = $Pos1 + 5                        ; "!ld" Zeichen entfernen neue Position   = 1146
;MsgBox (0, "neupos " , $neupos1)
   Global $Pos2 = StringInStr($strXML, "</lat")        ; Position von "</lat") im kleinen String = 1154
;MsgBox (0, "pos2 " , $pos2)
   Global $Dif1 = $Pos2 - $neuPos1                     ; Diferenz zwischen Position 1 und 2      = 8
;MsgBox (0, "Dif1 " , $dif1)
   Global $Lat = StringMid($strXML, $neuPos1, $Dif1)  ;  Lat Position für Navi                   = 54.985112
;MsgBox (0, "Lat " , $Lat)

;Berechnung Lon
   Global $Pos1 = StringInStr($strXML, "<lon>")        ; Position von ""<lon>")")im großen String  = 1169
;MsgBox (0, "pos1 " , $pos1)
   Global $neuPos1  = $Pos1 + 5                        ; "!ld" Zeichen entfernen neue Position     = 1174
;MsgBox (0, "neupos " , $neupos1)
   Global $Pos2 = StringInStr($strXML, "</lon"  )      ; Position von "</lon" im kleinen String    = 1181
;MsgBox (0, "pos2 " , $pos2)
   Global $Dif1 = $Pos2 - $neuPos1                     ; Diferenz zwischen Position 1 und 2        = 7
;MsgBox (0, "Dif1 " , $dif1)
   Global $Lon = StringMid($strXML, $neuPos1, $Dif1)  ;  Lat Position für Navi                     = 6.559423
;MsgBox (0, "Lon " , $Lon)

; Wert in Spalte I schreiben
   _Excel_RangeWrite ($oWorkbook, $oWorkbook.Activesheet, $Lat, "I" &$R)
   _Excel_RangeWrite ($oWorkbook, $oWorkbook.Activesheet, $Lon, "J" &$R)
    $oExcel.Columns("A:J").AutoFit  ; Blatt auf Zellenbreite formatieren
Next
Local $PID = ProcessExists("iexplore.exe")      ; Internet Explorer schließen
   If $PID Then ProcessClose($PID)                 ; PID schlißt den IExplorer
EndFunc


Func AATour()
; Funtion AATour.gpx anlegen und einlesen
   Global $GPXdatei = FileOpen ( $Zieldatei , 1 )
; GPX Kopf = $KText = Kopftext
    $KText  = "<?xml version="&'"'&1.0 &'"' &"?>" & @CRLF
    $KText &= "<gpx xmlns="&'"http://www.topografix.com/GPX/1/1"'& " creator="&'"TVG-Verlag"'&" version=" &'"1.1"'&" xmlns:xsi="&'"http://www.w3.org/2001/XMLSchema-instance"'  & @CRLF
    $KText &= "xsi:schemaLocation="&'"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"'&">"  & @CRLF
    $KText &= "	<metadata>"  & @CRLF
    $KText &= "		<link href="&'"http://www.tvg-verlag.de/"'&">" & @CRLF
    $KText &= "			<text>TVG-Verlag</text></link>"  & @CRLF
    $KText &= "	</metadata>"  & @CRLF
    $KText &= "	<rte>" & @CRLF
    $KText &= "		<name>RouteNavigator Europa - Route</name>" & @CRLF
    $KText &= "        <desc></desc>"  & @CRLF
 FileWrite ( $GPXdatei , $KText )

Global $R = 2
For $R = 2 To $Zzahl
   Global $Nummer  = _Excel_RangeRead($oWorkbook, Default, "A" &$R)
   Global $Name    = _Excel_RangeRead($oWorkbook, Default, "B" &$R)
   Global $Strasse = _Excel_RangeRead($oWorkbook, Default, "C" &$R)
   Global $Plz     = _Excel_RangeRead($oWorkbook, Default, "D" &$R)
   Global $Ort     = _Excel_RangeRead($oWorkbook, Default, "E" &$R)
   Global $Late    = _Excel_RangeRead($oWorkbook, Default, "I" &$R)
   Global $Lone    = _Excel_RangeRead($oWorkbook, Default, "J" &$R)
   Global $Lati =    String ($Late)
   Global $Loni =    String ($Lone)
   Global $Lona = StringRegExpReplace ( $Loni , "\ r \ n | \ r | \ n" , "" )
   Global $Lata = StringRegExpReplace ( $Late , "\ r \ n | \ r | \ n" , "" )

; String $SText für Lat und Lon
Global $SText = "<rtept lat="&'"'&$Lata &'"'&" "&"lon="&'"'&$Lona &'"'&">" &@CRLF
FileWrite ( $GPXdatei , $SText )
; String $AText ist Adresse
Global $AText = "<name>" &$Nummer &"; " &$Name &"; " &$Plz &" "&$Ort &"</name>"   &@CRLF
FileWrite ( $GPXdatei , $AText )
; String $ZText für zwischen den Kunden
Global $ZText = "</rtept>"
FileWrite ( $GPXdatei , $ZText )

Next
; String $Etext für Abschlußtext
$EText  =	"</rte>" &@CRLF
$EText &= "</gpx>" &@CRLF
FileWrite ( $GPXdatei , $EText )
;Datei AATour.pgx schließen
FileClose ( $GPXdatei )
;Datei nach ITN Converter
ShellExecute( $Zieldatei  )

Converter() ; ITN Converter Funtion

EndFunc

Func Converter()
 ; ITN Converter Fenster
   WinActivate("ITN Converter", "")
   WinWaitActive("ITN Converter","")
   Global $hWnd = WinGetHandle("ITN Converter")
   ControlClick($hWnd, "", "[CLASS:ComboBox; INSTANCE:1]")

; Exportieren Button
   ControlClick($hWnd, "", "[Class:Button;Instance:3]")
; Fenster Exportieren
   WinActivate("Exportieren", "")
   WinWaitActive("Exportieren","")
   Global $hWnd = WinGetHandle("Exportieren")
   Sleep (500)
   ControlClick($hWnd, "", "[Class:Button;Instance:2]")
; ITN Converter schließen
   Global $hWnd = WinGetHandle("ITN Converter")
   ControlClick($hWnd, "", "[Class:Button;Instance:1]")

; Tom Tom Link zum einfügen in Navi öffnen
  Global $IE = _IECreate("http://169.254.255.1/pcmi/?locale=de_de")
  _IELoadWait($IE)
  Sleep (1000)
EndFunc


Func Dateien_loeschen()
   FileDelete ("AATour.gpx")
   FileDelete ("Koordinaten.XML")
   FileDelete ("AATour.ov2")
EndFunc











