
#include <GUIConstants.au3>
#include <File.au3>
#include <Array.au3>

AutoItSetOption("TrayIconHide", 1)
AutoItSetOption("MustDeclareVars", 1)
AutoItSetOption("GUIOnEventMode", 1)

Global Const $INIFILE = "Cont_CEx.ini"
Global $cfg_outPath
Global $cfg_outPathBackup= ""
Global $cfg_WinZipPath
Global $cfg_EditorPath
Global $cfg_cboxShow_SW_List
Global $g_altDestPath= @TempDir
;MsgBox(0, "$altDestPath", $altDestPath)
;Global $cfg_cboxSave_SW_List

Global $inpOutPath
Global $btnOutPath
Global $inpSourceFile
Global $inpWinZip
Global $inpEditor
Global $cboxShow_SW_List
Global $cboxSave_SW_List

Global $edtOutput
;Global $prgProgressBar
Global $btnStart
Global $gfl_ShowSW_List= 0
Global $gfl_SaveSW_List= 1
Global $Cont_Name= ""
Global $Cont_Path= ""

buildGUI()
loadConfig()
writeToGUI()
GUISetState() ; Programmfenster sichtbar machen

If $CmdLine[0] > 0 Then
	GUICtrlSetData($inpSourceFile, $CmdLine[1])
	evtStart()
EndIf

While 1
	Sleep(1000) ; Endlosschleife für den On-Event-Modus
WEnd
; ----- Ende des Hauptprogramms

;================================================
;GUI
;================================================
Func buildGUI()
	GUICreate("Content Extractor v0.1.3", 500, 400)
	GUISetFont(10, 400, 0, "Sans Serif")
	
	$edtOutput = GUICtrlCreateEdit("", 0, 221, 500, 120, $ES_READONLY + $ES_MULTILINE + $WS_VSCROLL + $ES_AUTOVSCROLL)
	;$prgProgressBar = GUICtrlCreateProgress(10, 361, 340, 20)
	;$btnStart = GUICtrlCreateButton("Start", 380, 360, 100, 24) ;Button links
	$btnStart = GUICtrlCreateButton("Start", 5, 360, 100, 24) ;Button rechts
	
	
	;=========
	; Tab Main
	Local $tab = GUICtrlCreateTab(0, 0, 500, 220)
	Local $tabMain = GUICtrlCreateTabItem("Main")
	GUICtrlCreateLabel("Cont-Container", 10, 40, 119, 20)
	$inpSourceFile = GUICtrlCreateInput("", 100, 40, 350, 22, $ES_READONLY)
	Local $btnSourceFile = GUICtrlCreateButton("...", 460, 40, 20, 20)
	
	GUICtrlCreateLabel("Zielordner", 10, 80, 119, 20)
	$inpOutPath = GUICtrlCreateInput("", 100, 80, 350, 22, $ES_READONLY)
	$btnOutPath = GUICtrlCreateButton("...", 460, 80, 20, 20)
	
	;==============
	; Tab Programme
	Local $tabConfig = GUICtrlCreateTabItem("Programme")
	GUICtrlCreateGroup("Programmpfade festlegen", 10, 30, 480, 175)
	GUICtrlCreateLabel("WinZip", 16, 50, 119, 20)
	$inpWinZip = GUICtrlCreateInput("", 120, 50, 330, 22, $ES_READONLY)
	Local $btnWinZip = GUICtrlCreateButton("...", 460, 50, 20, 20)
	GUICtrlCreateLabel("Editor", 16, 90, 119, 20)
	$inpEditor= GUICtrlCreateInput("", 120, 90, 330, 22, $ES_READONLY)
	Local $btnEditor = GUICtrlCreateButton("...", 460, 90, 20, 20)
	;Local $btnRefresh = GUICtrlCreateButton("Übernehmen", 380, 180, 100, 20)
	
	;============
	;Tab Settings
	Local $tabConfig = GUICtrlCreateTabItem("Settings")
	GUICtrlCreateGroup("Programmeinstellungen", 10, 30, 480, 175)
	;GUICtrlCreateLabel("SW Liste nach Erstellung mit Texteditor anzeigen", 16, 50, 119, 20)
	;GUICtrlCreateLabel("SW Liste nach Erstellung mit Texteditor anzeigen", 20, 50, 300, 20)
	$cboxShow_SW_List= GuiCtrlCreateCheckbox("SW Liste nach Erstellung mit Texteditor anzeigen (persistent)", 20, 50, 400, 20)
	$cboxSave_SW_List= GuiCtrlCreateCheckbox("SW Liste nach Erstellung nicht im Zielordner speichern (nicht persistent)", 20, 70, 450, 20)
	;Local $btnRefresh = GUICtrlCreateButton("Übernehmen", 380, 180, 100, 20)

	;=============================
	; Ereignis-Funktionen zuordnen
	GUISetOnEvent($GUI_EVENT_CLOSE, "evtExit")
	GUICtrlSetOnEvent($btnSourceFile, "evtSourceFile")
	GUICtrlSetOnEvent($btnOutPath, "evtOutPath")
	GUICtrlSetOnEvent($btnWinZip, "evtWinZipPath")
	GUICtrlSetOnEvent($btnEditor,  "evtEditorPath")
	GUICtrlSetOnEvent($btnStart, "evtStart")
	GUICtrlSetOnEvent($cboxShow_SW_List, "evtCB_ShowSW_List")
	GUICtrlSetOnEvent($cboxSave_SW_List, "evtCB_SaveSW_List")
EndFunc   ;==>buildGUI
;ENDE GUI 
;================================================


;================================================
;EVENT FUNKTIONEN
;================================================
;==>evtSourceFile
Func evtSourceFile()
	chooseFile($inpSourceFile, "Cont-Container auswählen...", "Cont-Datei (*.Cont)")
EndFunc   


;=============
;==>evtOutPath
Func evtOutPath()
	Local $folder = FileSelectFolder("Ausgabe-Verzeichnis auswählen...", "", 2)
	If $folder <> "" Then
		GUICtrlSetData($inpOutPath, $folder)
	EndIf
EndFunc   

;================
;==>evtWinZipPath
Func evtWinZipPath()
	chooseFile($inpWinZip, "WinZip auswählen...", "Ausführbare Datei (*.exe)")
EndFunc   

;================
;==>evtEditorPath
Func evtEditorPath()
	chooseFile($inpEditor, "Texteditor auswählen...", "Ausführbare Datei (*.exe)")
EndFunc

;=====================
;==>Dateiauswahldialog
Func chooseFile($inpField, $strTitle, $strFilter)
	Local $file = FileOpenDialog($strTitle, "", $strFilter, 1)
	If $file <> "" Then
		GUICtrlSetData($inpField, $file)
		;MsgBox(0, "$inpField", $inpField)
	EndIf
EndFunc

;==================
; Fenster schließen
Func evtExit() 
	readFromGUI()
	saveConfig()
	Exit
EndFunc   ;==>evtExit
;MsgBox(0, "$cfg_cboxShow_SW_List", $cfg_cboxShow_SW_List)

;===========
; Startknopf
Func evtStart() 
	readFromGUI()
	If Not checkTools() Then
		Return
	EndIf
	;CheckOptionSettings()
	saveConfig()
	
	if $gfl_SaveSW_List == 0 Then
		$cfg_outPath= $g_altDestPath ;-> Temporäres Verzeichnis
	EndIf
	GUICtrlSetState($btnStart, $GUI_DISABLE)
	ContentExtract(GUICtrlRead($inpSourceFile), $cfg_outPath)
	GUICtrlSetState($btnStart, $GUI_ENABLE)
EndFunc   ;==>evtStart

;=========================================
; Checkbox SW_List im Texteditor anzeigen
Func evtCB_ShowSW_List()
	;MsgBox(0, "$cboxShow_SW_List", $cboxShow_SW_List)
	 readFromGUI()
	 If GUICtrlRead($cboxShow_SW_List) = $GUI_CHECKED Then
		If FileExists ($cfg_EditorPath) Then 
			;MsgBox(0, "evt Pfad2","")
			$gfl_ShowSW_List= 1
			$cfg_cboxShow_SW_List= 1
			GUICtrlSetState($cboxSave_SW_List, $GUI_ENABLE) 
		Else
			$gfl_ShowSW_List= 0
			$cfg_cboxShow_SW_List= 0
			;MsgBox(0, "evt Pfad3","")
			MsgBox(0, "FEHLER: Kein Texteditor angegeben!", "Um diese Option zu nutzen, muss im Reiter 'Programme' ein Texteditor angegeben werden.")
			GUICtrlSetState($cboxShow_SW_List, $GUI_UNCHECKED) 
			GUICtrlSetState($cboxSave_SW_List, $GUI_DISABLE) 
		EndIf
	 Else
		; MsgBox(1, "evt Pfad4","")
		 $gfl_ShowSW_List= 0
		 $cfg_cboxShow_SW_List= 0 
		 GUICtrlSetState($cboxSave_SW_List, $GUI_DISABLE) 
	EndIf
EndFunc

;==================================================
; Checkbox SW_List nach Erstellung nicht speichern
Func evtCB_SaveSW_List()
		 readFromGUI()
	 If GUICtrlRead($cboxSave_SW_List) = $GUI_CHECKED Then
		$gfl_SaveSW_List= 0
		GUICtrlSetState($inpOutPath, $GUI_DISABLE)
		GUICtrlSetState($btnOutPath, $GUI_DISABLE)
		$cfg_outPathBackup= $cfg_outPath; 
		;$cfg_outPath= $g_altDestPath ;-> Temporäres Verzeichnis
		;MsgBox(0, "$cfg_outPath", $cfg_outPath)
	 Else
		$gfl_SaveSW_List= 1
		GUICtrlSetState($inpOutPath, $GUI_ENABLE)
		GUICtrlSetState($btnOutPath, $GUI_ENABLE)
;~ 		if $cfg_outPathBackup <> "" Then
;~ 			$cfg_outPath= $cfg_outPathBackup
;~ 		EndIf
	EndIf
EndFunc
;ENDE Ereignisfunktionen
;================================================

;================================================
;KONFIG FUNKTIONEN
;================================================
 ;==>loadConfig
Func loadConfig()
	$cfg_outPath = IniRead(@ScriptDir & "\" & $INIFILE, "Paths", "Output", $g_altDestPath)
	$cfg_WinZipPath= IniRead(@ScriptDir & "\" & $INIFILE, "Paths", "WinZip", "") 
	$cfg_EditorPath= IniRead(@ScriptDir & "\" & $INIFILE, "Paths", "Editor", "") 
	$cfg_cboxShow_SW_List= IniRead(@ScriptDir & "\" & $INIFILE, "Options", "CB_ShowSW_List", "") 
	if $cfg_cboxShow_SW_List == 1 Then
		$gfl_ShowSW_List= 1
	EndIf
EndFunc  

 ;==>saveConfig
Func saveConfig()
	if $cfg_outPathBackup <> "" then
		IniWrite(@ScriptDir & "\" & $INIFILE, "Paths", "Output", $cfg_outPathBackup)
	Else
		IniWrite(@ScriptDir & "\" & $INIFILE, "Paths", "Output", $cfg_outPath)
	EndIf
	IniWrite(@ScriptDir & "\" & $INIFILE, "Paths", "WinZip", $cfg_WinZipPath)
	IniWrite(@ScriptDir & "\" & $INIFILE, "Paths", "Editor", $cfg_EditorPath)
	IniWrite(@ScriptDir & "\" & $INIFILE, "Options", "CB_ShowSW_List", $cfg_cboxShow_SW_List)
EndFunc  

;==>writeToGUI
Func writeToGUI()
	GUICtrlSetData($inpOutPath, $cfg_outPath)
	GUICtrlSetData($inpWinZip, $cfg_WinZipPath)
	GUICtrlSetData($inpEditor, $cfg_EditorPath)
	if $cfg_cboxShow_SW_List == 1 Then
		GUICtrlSetState($cboxShow_SW_List, $GUI_CHECKED) 
		GUICtrlSetState($cboxSave_SW_List, $GUI_ENABLE) 
		if $cboxSave_SW_List == 0 Then
			GUICtrlSetState($cboxSave_SW_List, $GUI_CHECKED) 
		Else
			GUICtrlSetState($cboxSave_SW_List, $GUI_UNCHECKED) 
		EndIf
	Else
		GUICtrlSetState($cboxShow_SW_List, $GUI_UNCHECKED)
		GUICtrlSetState($cboxShow_SW_List, $GUI_UNCHECKED)
		GUICtrlSetState($cboxSave_SW_List, $GUI_DISABLE) 
	EndIf
EndFunc   

;==>readFromGUI
Func readFromGUI()
	$cfg_outPath = GUICtrlRead($inpOutPath)
	$cfg_WinZipPath= GUICtrlRead($inpWinZip)
	$cfg_EditorPath= GUICtrlRead($inpEditor)
	$cfg_cboxShow_SW_List= GUICtrlRead($cboxShow_SW_List)
	if $cfg_cboxShow_SW_List == 1 Then
		$gfl_ShowSW_List= 1
	EndIf
	;MsgBox(0, "$cfg_cboxShow_SW_List", $cfg_cboxShow_SW_List)
EndFunc   
;Ende Konfigfunktionen
;================================================

;================================================
;HAUPTFUNKTIONEN
;================================================
Func ContentExtract($sourceFile, $destinationPath)
	Local $appName= "WinZip Pro"
	Local $cmd= "cmd.exe"
	Local $appWZ_extract= " -e"
	Local $appWZ_min= " -min" ; run minimized
	Local $appWZ_sub = " -o"; bestehende Dateien überschreiben
	Local $appWinZipOptions= $appWZ_min & $appWZ_extract & $appWZ_sub
	Local $appExecute= $cfg_WinZipPath & $appWinZipOptions & " " & $sourceFile & " " & $destinationPath
	Local $Cont_strName= ""
	;Local $Cont_Path=""
	Local $add_btld= "SW\btld"
	Local $add_cafd= "SW\cafd"
	Local $add_swfl= "SW\swfl"
	Local $btldPath= "" 
	Local $cafdPath= "" 
	Local $swflPath= "" 
	Local $btldList= ""
	Local $cafdList= ""
	Local $swflList= ""
	;Local $swflListData= ""
	Local $SW_ListName= ""
	Local $FileNamePrep= "SW_List_"
	Local $FileExt= ".txt"
	Local $SW_ListlongName= ""
	Local $hFile= ""
	
	;MsgBox(1,"$sourceFile",$sourceFile)

	;Tools prüfen
	If Not checkTools() Then
		Return
	EndIf
	
	;Sourcefile Existenz prüfen 
	If $sourceFile == "" Then
		;print("Fehler: Kein Cont-Container angegeben")
		MsgBox(0, "FEHLER: Kein Cont-Container angegeben!", "Im Reiter 'Main' wurde kein Cont-KC angegeben.");
		print ("----- Abbruch -----")
		Return 
	ElseIf Not FileExists($sourceFile) Then
		;print("Fehler: Quelldatei existiert nicht")
		MsgBox(0, "FEHLER: Cont_Container existiert nicht!", "Der im Reiter 'Main' angegebene Cont-KC existiert nicht.");
		print ("----- Abbruch -----")
		Return
	ElseIf Not FileExists($cfg_outPath) Then
		MsgBox(0, "FEHLER: Zielordner existiert nicht!", "Der im Reiter 'Main' angegebene Zielordner existiert nicht. Pfad überprüfen, oder Option 'SW Liste nach Erstellung nicht im Zielordner speichern' aktivieren")
		print ("----- Abbruch -----")
		Return
	;Pfade zusammenbauen
	Else
		$Cont_Name= getFileName($sourceFile)
		;MsgBox(1, "$Cont_Name", $Cont_Name)
		$Cont_strName= StringReplace($Cont_Name, ".","_",0)
		;MsgBox(1,"$Cont_strName",$Cont_strName)
		$Cont_Path= $destinationPath & "\" & $Cont_strName
		;MsgBox(1,"$Cont_Path",$Cont_Path)
		$btldPath= $Cont_Path & "\" & $add_btld
		;MsgBox(1,"$btldPath",$btldPath)
		$cafdPath= $Cont_Path & "\" & $add_cafd
		;MsgBox(1,"$cafdPath",$cafdPath)
		$swflPath= $Cont_Path & "\" & $add_swfl
		;MsgBox(1,"$swflPath",$swflPath)
		$SW_ListName= $FileNamePrep & $Cont_strName & $FileExt 
		;MsgBox(1,"$FileName",$FileName)
		$SW_ListlongName= $destinationPath & "\" & $SW_ListName
		;MsgBox(1,"$SW_ListlongName",$SW_ListlongName)
	EndIf
	

	;
	print("----- Start -----")
	print("Extrahiere Cont-Container...");
	RunWait($appExecute, "", @SW_HIDE) ;Cont-Container mit WinZip extrahieren
	WinClose($appName)
	
	print("Generiere SW Liste...")
	$btldList= _FileListToArray($btldPath)
	If @Error=4 Then
		print("-> Container enthält keinen Bootloader")
	EndIf
	;_ArrayDisplay($btldList,"$btldList")
	
	$cafdList=  _FileListToArray($cafdPath)
	If @Error=4 Then
		print("-> Container enthält keine Codierdatei")
	EndIf
	
	$swflList= _FileListToArray($swflPath)
	If @Error=4 Then
		print("-> Container enthält keine Softwareeinheiten")
	EndIf
	
;	_ArrayDisplay($swflList,"$swflList")
	
	
	print("Lösche temporäre Dateien...")
	deleteTempFiles($sourceFile, $destinationPath)
	
	
	
	_FileWriteFromArray($SW_ListlongName, $btldList, 1)
	$hFile = FileOpen($SW_ListlongName, 1) ; 1 = append
		_FileWriteFromArray($hFile, $cafdList, 1)
		_FileWriteFromArray($hFile, $swflList, 1)
	FileClose($hFile)
	
	
	
	if $gfl_ShowSW_List == 1 Then
		run($cfg_EditorPath & " " & $SW_ListlongName)
	EndIf
	
	print("----- Fertig -----")
EndFunc   ;==>ContentExtract
;ENDE Hauptfunktionen
;================================================


;================================================
;CHECK TOOLS
;================================================
Func checkTools()
	;ZIP Proggy Existenz prüfen
	If Not FileExists($cfg_WinZipPath) Then
		;print("Fehler: In den Settings ist kein Pfad für WinZip angegeben")
		MsgBox(0, "FEHLER: Kein WinZIP Programmpfad angebeben!", "WinZip Programmpfad im Reiter 'Programme' angeben.")
		print ("----- Abbruch -----")
		Return False
	EndIf

	;Texteditor Existenz prüfen
	If $gfl_ShowSW_List == 1 Then 
		If Not FileExists($cfg_EditorPath) Then
			$gfl_ShowSW_List= 0
			$cfg_cboxShow_SW_List= 0 
			;GUICtrlSetState($cboxSave_SW_List, $GUI_DISABLE) 
			$inpEditor= ""
			writeToGUI()
			MsgBox(0,"FEHLER: Texteditor nicht gefunden!", "Im Reiter 'Programme' Editorpfad überprüfen.")
			print("----- Abbruch -----")
			Return False
		EndIf
		;MsgBox(0, "Editorcheck ok, $gfl_ShowSW_List soll 1", $gfl_ShowSW_List)
	EndIf
	
	Return True
EndFunc

;Prüfen, ob die in den Settings eingestellten
;Optionen asynchron verändert wurden
;~ Func CheckOptionSettings()
;~ 	readFromGUI()
;~ 	;Verhindern, dass durch manuelles Entfernen des Editors die Option ausgeführt wird
;~ 	If GUICtrlRead($cboxShow_SW_List) = $GUI_CHECKED Then
;~ 			 ;MsgBox(1, "SW_Liste anzeigen","")
;~ 			If FileExists ($cfg_EditorPath) Then 
;~ 				$gfl_ShowSW_List= 1
;~ 				$cfg_cboxShow_SW_List= 1
;~ 			Else
;~ 				$gfl_ShowSW_List= 0
;~ 				$cfg_cboxShow_SW_List= 0
;~ 				;MsgBox(0, "FEHLER: Kein Texteditor angegeben", "Um diese Option zu nutzen, muss im Reiter 'Programme' ein Texteditor angegeben werden")
;~ 				print("<Kein Texteditor gefunden => Ergebnisanzeige deaktiviert>")
;~ 				GUICtrlSetState($cboxShow_SW_List, $GUI_UNCHECKED) 
;~ 				$gfl_ShowSW_List= 0
;~ 			EndIf
;~ 	Else
;~ 		$gfl_ShowSW_List= 0
;~ 		$cfg_cboxShow_SW_List= 0 
;~ 	EndIf
;~ 		 
;~ EndFunc
;ENDE CheckTools
;========================================


;================================================
;AUFRÄUMEN
;================================================
Func deleteTempFiles($sourceFile, $destinationPath)
;~ 	FileDelete($destinationPath & "\" & getFileName($sourceFile) & ".mpg")
	DirRemove($Cont_Path, 1) 
	;MsgBox(1, "$destinationPath",$destinationPath)
	FileDelete($destinationPath & "\" & "*.xml")
EndFunc   ;==>deleteTempFiles

;================================================
; HILFSFUNKTIONEN
;================================================
;==>getFileName
Func getFileName($path)
	Local $array[4]
	$array = pathSplit($path)
	;MsgBox(1, "getFileName Ergebnis", $array[3])
	Return $array[3]
EndFunc   
 
 ;==>getExtension
Func getExtension($path)
	Local $array[4]
	$array = pathSplit($path)
	Return $array[4]
EndFunc  

;==>getPathWithoutExtension
Func getPathWithoutExtension($path)
	Local $array[4]
	$array = pathSplit($path)
	Return $array[1] & $array[2] & $array[3]
EndFunc   

; Nutzt die Bibliotheksfunktion _PathSplit, liefert nur das Array mit den Ergebnissen zurück
Func pathSplit($path)
	Local $drive, $dir, $fname, $ext
	Return _PathSplit($path, $drive, $dir, $fname, $ext)
EndFunc   ;==>pathSplit

;Liefert den Ergebnis-String, auf den der reguläre Ausdruck matcht.
Func regExMatch($string, $regex)
	Local $array[1]
	$array = StringRegExp($string, $regex, 1)
	If @error = 0 Then
		Return $array[0]
	Else
		Return 0
	EndIf
EndFunc   ;==>regExMatch

;==>print
Func print($text)
	GUICtrlSetData($edtOutput, GUICtrlRead($edtOutput) & $text & @CRLF)
EndFunc   

;Quelle: http://snippets.dzone.com/posts/show/4680
;Meldung an DebugView kann man mit dem Sysinternals-Werkzeug DebugView einsehen
Func debug($msg, $error = @error, $extended = @extended, $ScriptLineNumber = @ScriptLineNumber)
	Local $out = "-debug- " & $msg & ", Zeile:" & $ScriptLineNumber & ", Fehler: " & $error & " " & $extended
	;Output to application attaching a console to the script engine
	ConsoleWrite($out & @CRLF)
	;Output to debugger (dbgview.exe)
	DllCall("kernel32.dll", "none", "OutputDebugString", "str", $out)
EndFunc   ;==>debug
;debug("Fehler: " & $return & "existiert nach Konvertierung nicht")

;ENDE Hilfsfunktionen 
;=============================================================================