#include <Array.au3>
#include <File.au3>
#include <GUIConstantsEx.au3>

local $oReceived, $SessionKey, $SurveyID, $Decoded, $CSVArray, $csv_array_0, $csv_array_1, $csv_array_merge
global $csvFileList

;------------------------------------------------
$URL = "https://surveyURL/index.php/admin/remotecontrol"

$user = "user"
$pwd = "pass"
;------------------------------------------------

;---read path from ini file---------------------
$Folderpath = IniRead(@ScriptDir & "\bin\limesurvey.ini", "folderpath", "path", "Default Value") 
;MsgBox(0,"",$Folderpath)
;------------------------------------------------

;---- Survey ID's array from ini file--------------------------

$Survey_iniArray = IniReadSection(@ScriptDir & "\bin\limesurvey.ini", "survey")
;_ArrayDisplay($Survey_iniArray)

; ------------------------------------------------

$hGUI = GUICreate("LimeSurvey Remote  " & FileGetVersion(@ScriptName),380, 90)

$connection_color_red = GUICtrlCreateGraphic(15, 70, 8, 8, 0)
GUICtrlSetBkColor($connection_color_red, 0xf21b0c)

$connection_color_green = GUICtrlCreateGraphic(25, 70, 8, 8, 0)
GUICtrlSetBkColor($connection_color_green, 0xcacfc8) ;set to grey 0xcacfc8

$btn_get_session_key = GUICtrlCreateButton("connect", 30, 25, 100, 25)
GUICtrlSetTip($btn_get_session_key, "get_session_key")

$btn_add_participants = GUICtrlCreateButton("add_participants", 140, 25, 100, 25)
GUICtrlSetState($btn_add_participants,$GUI_DISABLE)
GUICtrlSetTip($btn_add_participants, "add_participants")

$btn_export_responses = GUICtrlCreateButton("export_responses", 250, 25, 100, 25)
GUICtrlSetState($btn_export_responses,$GUI_DISABLE)
GUICtrlSetTip($btn_export_responses, "export_responses")

$txt_sessionkey = GUICtrlCreateLabel("",65,65, 300, 70)
GUICtrlSetColor($txt_sessionkey, 0xcacfc8)

; Display the GUI.
GUISetState(@SW_SHOW, $hGUI)

; Loop until the user exits.
While 1
    Switch GUIGetMsg()
		Case $GUI_EVENT_CLOSE
              ExitLoop

		Case $btn_get_session_key

			_get_session_key()

			;MsgBox(0,"Session Key",$SessionKey,1)
			GUICtrlSetData($txt_sessionkey ,"session: " & $SessionKey)
			GUICtrlSetBkColor($connection_color_green, 0x00ad11) ; set to green 0x00ad11)
			GUICtrlSetBkColor($connection_color_red, 0xcacfc8) ; set to grey 0xcacfc8

			GUICtrlSetState($btn_add_participants,$GUI_ENABLE)
			GUICtrlSetState($btn_export_responses,$GUI_ENABLE)
			GUICtrlSetState($btn_get_session_key,$GUI_DISABLE)


		Case $btn_add_participants
			_list_csv_files()
			;_ArrayDisplay($csvFileList)
			_add_participants()

			;------- move files to Archive folder ------------
			For $f = 1 to UBound($csvFileList) -1
				MsgBox(0,"", "move file to Archive: " & $csvFileList[$f],2)
				FileMove( $Folderpath & "\" & $csvFileList[$f],$Folderpath & "\Archive\",1)
			Next
			; ------------------------------------------------
			GUICtrlSetState($btn_add_participants, $GUI_DISABLE)

		Case $btn_export_responses

			If not FileExists ($Folderpath & "\results_temp") Then DirCreate ($Folderpath & "\results_temp")

			For $g = 1 To UBound($Survey_iniArray) -1
				MsgBox(0, "Info", $Survey_iniArray[$g][0] & " - " & $Survey_iniArray[$g][1])

				;----------------------------------------------------------
 				_export_responses($Survey_iniArray[$g][0],0) ;parameter = survey id + ohne Zusatz attribute
				$exp_response_0 = BinaryToString($Decoded,4)
				_csv_file_create($Survey_iniArray[$g][1],0) ;parameter = survey portal + ohne Zusatz attribute
				;----------------------------------------------------------
				_export_responses($Survey_iniArray[$g][0],1) ;parameter = survey id + mit Zusatz attributen
				$exp_response_1= BinaryToString($Decoded,4)
				_csv_file_create($Survey_iniArray[$g][1],1);parameter = survey portal+ mit Zusatz attributen
				;----------------------------------------------------------

 				_csv_files_merge($Survey_iniArray[$g][1])  ; merge csv files - portal

			Next

			DirRemove($Folderpath & "\results_temp",1)
			GUICtrlSetState($btn_export_responses,$GUI_DISABLE)

    EndSwitch
WEnd

; Delete the previous GUI and all controls.
GUIDelete($hGUI)
Exit


Func _add_participants() ; add participants to lime survey ID

	For $b = 1 to UBound($csvFileList) -1

		$portal = StringSplit($csvFileList[$b],"_")
		;_ArrayDisplay($portal)
		;MsgBox(0,"Portal",$portal[2]); Portal read from CSV File

		For $c = 1 To UBound($Survey_iniArray) -1

			IF $portal[2] = $Survey_iniArray[$c][1] Then
				$SurveyID = $Survey_iniArray[$c][0]
				MsgBox(0,"Info","Portal: " & $portal[2] & @CRLF & "Survey ID: " & $SurveyID)
			EndIf
		Next

		;----csv read to array---
		_FileReadToArray($Folderpath & "\" & $csvFileList[$b], $CSVArray)
		;_ArrayDisplay($CSVArray)

		For $d = 2 to UBound($CSVArray) -1

			$csv_splitt = StringSplit($CSVArray[$d],";")
			;_ArrayDisplay($csv_splitt)

			_list_participants($csv_splitt[1]) ; lese participants, wenn bereits mit id vorhanden überspringe diesen
			;ConsoleWrite($oReceived)  ;Rückgabewert

			$participants_Return = StringSplit($oReceived,",")
			$participants_Return = StringSplit($participants_Return[2],",:")
			;_ArrayDisplay($participants_Return)

			$search_survey_participants = _ArraySearch($participants_Return, "No survey participants found.",0,0,0,1)

			If $search_survey_participants = -1 Then
				;MsgBox(0, $search_survey_participants, "bereits enthalten")
			Else

				$json_add_participants = ""

				$json_add_participants = '{"method": "add_participants",' & _
							'"params": {"sSessionKey": ' & $SessionKey & ',' & _
							'"iSurveyID": ' & $SurveyID & ' ,' & _
							'"aParticipantData": [{"attribute_1": "' & $csv_splitt[1] & '" ,' & _
												'"attribute_2": "' & $csv_splitt[2] & '" ,' & _
												'"firstname": "' & $csv_splitt[3] & '" ,' & _
												'"lastname": "' & $csv_splitt[4] & '" ,' & _
												'"email": "' & $csv_splitt[5] & '" ,' & _
												'"token": "customToken"}],"bCreateToken": "false"},"id": 1}'

				ConsoleWrite ($json_add_participants & @CRLF)
				_POST_DATA($URL, $json_add_participants)

			EndIf

		Next

		;MsgBox(0,"",$SurveyID)
		_mail_participants($SurveyID)  ; send mail to participants

	Next

EndFunc


Func _csv_file_create($SurveyID, $zF) ; csv_files_create + base64 decode

	;results-bigxtra
	$exportFile_xx = $Folderpath & "\results_temp\results-"& $SurveyID & "_" & $zF & ".csv"

	If FileExists($exportFile_xx) Then FileDelete($exportFile_xx)
	If Not FileExists($exportFile_xx) Then _FileCreate($exportFile_xx)

	FileWrite($exportFile_xx, BinaryToString($Decoded,4)); & @CRLF)

EndFunc


Func _csv_files_merge($Survey_Name) ; csv_files_create to array and merge 2 files in one csv

	$csv_array_merge = ""

	;----------------------------------------------------------------------
	$exportFile_merge = $Folderpath & "\results_temp\results-" & $Survey_Name & ".csv"

	If FileExists($exportFile_merge) Then FileDelete($exportFile_merge)
	If Not FileExists($exportFile_merge) Then _FileCreate($exportFile_merge)
	;----------------------------------------------------------------------

	$exportFile_0 = $Folderpath & "\results_temp\results-" & $Survey_Name & "_0.csv"
	$exportFile_1 = $Folderpath & "\results_temp\results-" & $Survey_Name & "_1.csv"

	_FileReadToArray($exportFile_0, $csv_array_0)  ; ohne Zusatzfelder
	;_ArrayDisplay($csv_array_0)

	_FileReadToArray($exportFile_1, $csv_array_1)	; mit Zusatzfeldern
	;_ArrayDisplay($csv_array_1)

	For $e = 1 to UBound($csv_array_1) -2

		$csv_array_1_splitt = StringSplit($csv_array_1[$e],";")

		$sRange = "0-12"
		_ArrayDelete($csv_array_1_splitt, $sRange)

		$csv_array_merge &= $csv_array_0[$e] &";"& $csv_array_1_splitt[0] &";"&  $csv_array_1_splitt[1] &";"&  $csv_array_1_splitt[2] &";"&  $csv_array_1_splitt[3] &";"& $csv_array_1_splitt[4] & @CR

	Next

	FileWrite($exportFile_merge, $csv_array_merge)

	FileDelete($exportFile_0)	;delete Results File1
	FileDelete($exportFile_1)	;delete Results File2

	MsgBox(0,"Info", 'move file "results-' & $Survey_Name & '.csv" to folder "Results"' ,2)
	FileMove($exportFile_merge,$Folderpath & "\Results\",1)  ;verschiebe File

EndFunc


Func _export_responses($SurveyID, $zF)  ; export_responses + base64 decode

	If $zF = 0 Then  ; ohne Zusatzfelder

	$json_export_responses = '{"method": "export_responses",' & _
				'"params": {"sSessionKey": ' & $SessionKey & ',' & _
				'"iSurveyID": ' & $SurveyID & ',' & _
				'"sDocumentType" : "csv",' & _
				'"sLanguageCode" : null,' & _
				'"sCompletionStatus" : "complete",' & _
				'"sHeadingType" : "code",' & _
				'"sResponseType" : "short"},' & _
				'"id": 1 }'
	EndIf
	If $zF = 1 Then ; mit Zusatzfeldern

	$json_export_responses = '{"method": "export_responses",' & _
				'"params": {"sSessionKey": ' & $SessionKey & ',' & _
				'"iSurveyID": ' & $SurveyID & ',' & _
				'"sDocumentType" : "csv",' & _
				'"sLanguageCode" : null,' & _
				'"sCompletionStatus" : "complete",' & _
				'"sHeadingType" : "code",' & _
				'"sResponseType" : "short",' & _
				'"aFields": ["id","submitdate","lastpage","startlanguage","seed","token","startdate","datestamp","refurl","G01Q01","G01Q02","G01Q03","firstname","lastname","email","attribute_1","attribute_2"]},' & _
				'"id": 1 }'
	EndIf
	ConsoleWrite ($json_export_responses & @CRLF)
	_POST_DATA($URL, $json_export_responses )
	;ConsoleWrite($oReceived)

	$export_Received = StringSplit($oReceived,'"')
	;_ArrayDisplay($export_Received)

	$Decoded = base64($export_Received[6], False)
	;ConsoleWrite(BinaryToString($Decoded,4) & @CRLF)

EndFunc


Func _mail_participants($SurveyID)  ; send mail to participants

	MsgBox(0,"","send mail to participants",1)
	;Send Mail to Umfrageteilnehmer
	$json_mail_participants = '{ "method": "mail_registered_participants", "params": [ ' & $SessionKey & ', "' & $SurveyID  & '" ], "id": 1 }'

	_POST_DATA($URL, $json_mail_participants)
	ConsoleWrite ($json_mail_participants & @CRLF)

EndFunc


Func _list_participants($attrib_1) ;lese Participants aus LimeSurvey mit Filter

	$json_list_participants = '{"method": "list_participants",' & _
				'"params": {"sSessionKey": ' & $SessionKey & ',' & _
				'"iSurveyID": ' & $SurveyID & ' ,' & _
				'"aAttributes": ["attribute_1"],' & _
				'"aConditions": {"attribute_1" : "'&$attrib_1&'"}},' & _  ;Filter auf Attribute_1
				'"id": 1 }'

	;ConsoleWrite ($json_list_participants & @CRLF)
	_POST_DATA($URL, $json_list_participants )
	;ConsoleWrite($oReceived)

EndFunc


Func _list_csv_files()  ;list csv files to array

	$csvFileList = _FileListToArray($Folderpath ,"*.csv",1)
	If @error = 1 Then
			MsgBox(0, "", "Path was invalid.")
			Exit
	EndIf
	If @error = 4 Then
			MsgBox(0, "", "No file(s) were found. Close Program")
			Exit
	EndIf

	_ArrayDisplay($csvFileList)

EndFunc


FUNC _get_session_key() ; get Lime Survey session key

	$json_get_session_key = '{ "method": "get_session_key", "params": [ "' & $user & '", "' & $pwd & '" ], "id": 1 }'

	_POST_DATA($URL, $json_get_session_key)

	$sString = $oReceived
	$sRegex = '(?<={"id":1,"result":)(?:{"status":"|")(.+?)(?="(?:}|),"error":null})'
	$aResult = StringRegExp($sString, $sRegex, 3)
	;_ArrayDisplay($aResult)

	$oReceived = $aResult[0]

	$oReceived_Error_1 = 'Invalid user name or password'
	$oReceived_Error_2 = 'Sie haben die maximale Anzahl an Anmeldeversuchen erreicht. Bitte warten Sie 10 Minuten, bevor Sie es erneut versuchen.'

	IF $oReceived = $oReceived_Error_1 Or $oReceived = $oReceived_Error_2 Then
		MsgBox(0,"Info",$oReceived & @crlf & @CRLF & "--> close Program")
		Exit
	EndIf

	;--- session key -------------------
	$SessionKey = '"' & $oReceived & '"'
	;-----------------------------------

EndFunc


FUNC _POST_DATA($URL, $JSON)  ; Post with URL & JSON DATA

	$oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
	$oHTTP.Open("POST", $URL, False)
	$oHTTP.SetRequestHeader("Content-Type", "application/json")
	$oHTTP.SetRequestHeader("Cache-Control", "no-cache")
	$oHTTP.Send($JSON)

	$oReceived = $oHTTP.ResponseText
	$oStatusCode = $oHTTP.Status

	If $oStatusCode <> 200 Then
		MsgBox(4096, "Error", $oStatusCode,2)
	EndIf
	;ConsoleWrite($oReceived)

EndFunc


;---------------------------------------------------------------------------------
; Ascer
;==============================================================================================================================
; Function:         base64($vCode [, $bEncode = True [, $bUrl = False]])
;
; Description:      Decode or Encode $vData using Microsoft.XMLDOM to Base64Binary or Base64Url.
;                   IMPORTANT! Encoded base64url is without @LF after 72 lines. Some websites may require this.
;
; Parameter(s):     $vData      - string or integer | Data to encode or decode.
;                   $bEncode    - boolean           | True - encode, False - decode.
;                   $bUrl       - boolean           | True - output is will decoded or encoded using base64url shema.
;
; Return Value(s):  On Success - Returns output data
;                   On Failure - Returns 1 - Failed to create object.
;
; Author (s):       (Ghads on Wordpress.com), Ascer
;===============================================================================================================================
Func base64($vCode, $bEncode = True, $bUrl = False)

    Local $oDM = ObjCreate("Microsoft.XMLDOM")
    If Not IsObj($oDM) Then Return SetError(1, 0, 1)

    Local $oEL = $oDM.createElement("Tmp")
    $oEL.DataType = "bin.base64"

    If $bEncode then
        $oEL.NodeTypedValue = Binary($vCode)
        If Not $bUrl Then Return $oEL.Text
        Return StringReplace(StringReplace(StringReplace($oEL.Text, "+", "-"),"/", "_"), @LF, "")
    Else
        If $bUrl Then $vCode = StringReplace(StringReplace($vCode, "-", "+"), "_", "/")
        $oEL.Text = $vCode
        Return $oEL.NodeTypedValue
    EndIf

EndFunc ;==>base64
;---------------------------------------------------------------------------------