INIT 0.2

INIT 0.2

#NoTrayIcon
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=images\twirl.ico
#AutoIt3Wrapper_Outfile=release\Get-Tweet.exe
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_Comment=SubteBA Telegram Alerter
#AutoIt3Wrapper_Res_Description=SubteBA Telegram Alerter
#AutoIt3Wrapper_Res_Fileversion=0.2.0.15
#AutoIt3Wrapper_Res_Fileversion_AutoIncrement=y
#AutoIt3Wrapper_Res_LegalCopyright=By Marcelo Saied
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#region init
	#NoTrayIcon
	#include <Misc.au3>
	If _Singleton(@ScriptName, 1) = 0 Then ; allow only one instance
		MsgBox(0, "Warning", "An occurence of " & @ScriptName & " is already running")
		Exit
	EndIf

	$SendToAll=0 ; si es 0 solo se manda a Dev users
					  ; si es 1 se manda a todos

	#include <includes\includes.au3>
	_ConfigInitial()
#endregion init

local $Username=IniRead("..\..\secret\config.ini","Twitter","Username","subteba")
while 1
	$htmltxt=_ScrapTweetMessages($Username)
	$TweetArr = _gettweetArr($htmltxt)
	if IsArray($TweetArr) then
		$newMessagesFlag=0
		For $i = 0 To UBound($TweetArr) -1
			$TweetID = $TweetArr[$i][0]
			$TweeMsg = $TweetArr[$i][1]
			$TweeDate = $TweetArr[$i][2]
			if not SQLExist_Message($TweetID) then
				SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
				sendmessages($TweeMsg)
				$newMessagesFlag=1
				ConsoleWrite('+ New messages ' & _NowTime(4) & @CRLF)
			endif
		Next
		if $newMessagesFlag=0 then ConsoleWrite('  No new messages ' & _NowTime(4) & @CRLF)
	endif

	UpdateUsers()

	$minutes=10
	ConsoleWrite('   sleeping '&$minutes& @CRLF)
	sleep($minutes*60*1000)
wend

closeall()

#NoTrayIcon
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=images\twirl.ico
#AutoIt3Wrapper_Outfile=release\Get-Tweet.exe
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_Comment=SubteBA Telegram Alerter
#AutoIt3Wrapper_Res_Description=SubteBA Telegram Alerter
#AutoIt3Wrapper_Res_Fileversion=0.1.0.15
#AutoIt3Wrapper_Res_Fileversion_AutoIncrement=y
#AutoIt3Wrapper_Res_LegalCopyright=By Marcelo Saied
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#region init
	#NoTrayIcon
	#include <Misc.au3>
	If _Singleton(@ScriptName, 1) = 0 Then ; allow only one instance
		MsgBox(0, "Warning", "An occurence of " & @ScriptName & " is already running")
		Exit
	EndIf

	$SendToAll=0 ; si es 0 solo se manda a Dev users
					  ; si es 1 se manda a todos

	#include <includes\includes.au3>
	_ConfigInitial()
#endregion init

local $Username=IniRead("..\..\secret\config.ini","Twitter","Username","subteba")
while 1
	$htmltxt=_ScrapTweetMessages($Username)
	$TweetArr = _gettweetArr($htmltxt)
	if IsArray($TweetArr) then
		$newMessagesFlag=0
		For $i = 0 To UBound($TweetArr) -1
			$TweetID = $TweetArr[$i][0]
			$TweeMsg = $TweetArr[$i][1]
			$TweeDate = $TweetArr[$i][2]
			if not SQLExist_Message($TweetID) then
				SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
				sendmessages($TweeMsg)
				$newMessagesFlag=1
				ConsoleWrite('+ New messages ' & _NowTime(4) & @CRLF)
			endif
		Next
		if $newMessagesFlag=0 then ConsoleWrite('  No new messages ' & _NowTime(4) & @CRLF)
	endif

	UpdateUsers()

	$minutes=10
	ConsoleWrite('   sleeping '&$minutes& @CRLF)
	sleep($minutes*60*1000)
wend

closeall()


fx message for /start

fx message for /start

#region ====INIT ===============================================================
	Func _ConfigInitial()
;~ 		ConsoleWrite('++ConfigDBInitial() = ' & @CRLF)
		_SQLite_down()
;~ 		_DBvarInit()
		; -------check if SQLIte SubteBA db exist
		SQLite_init()
		$SQLq = "SELECT name FROM sqlite_temp_master WHERE type='table';"
		_SQLITErun($SQLq, $dbfile, $quietSQLQuery)
	;~ 	;-------- Init Log
	;~ 	_initLog()
		;------------------------------------------------------------------------------
	EndFunc   ;==>_ConfigDBInitial
#endregion
#region  ==== SQL functions =======================================================================
	Func SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
;~ 		ConsoleWrite('++InsertMessageSQL() = '& @crlf)
		$query='INSERT INTO messages VALUES (' & $TweetID & ',"' & $TweeMsg & '" ,' & $TweeDate & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting mesages ErrNo 1010" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLGetUsers()
;~ 		ConsoleWrite('++SQLGetUsers() = '& @crlf)
		$query='SELECT * FROM Users ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetActiveUsers()
;~ 		ConsoleWrite('++SQLGetActiveUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetDevUsers()
;~ 		ConsoleWrite('++SQLGetDevUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 AND Dev=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLExist_Message($TweetID)
;~ 		ConsoleWrite('++Exist_Message() = '&$TweetID& @crlf)
		$query='SELECT id FROM messages WHERE id="'&$TweetID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
#endregion
#region  ==== send messages =======================================================================
;~  	Func sendmessages($message)  ;~ from file of recipients
;~ 		Local $fileh = FileOpen("secret\recipients.txt", 0)
;~ 		If $fileh = -1 Then
;~ 			Exit 26
;~ 		EndIf
;~ 		While 1
;~ 			Local $chatidLine = FileReadLine($fileh)
;~ 			If @error = -1 Then ExitLoop
;~ 			$chatidArr = StringSplit($chatidLine, ',')
;~ 			$chatid = $chatidArr[1]
;~ 			if $chatID<>"" then
;~ 				ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $chatidArr[2] & @CRLF)
;~ 				$respuesta = SendTelegramexec($chatid,$message)
;~ 			$respuesta  0 is ok
;~ 			endif
;~ 		WEnd
;~ 		FileClose($fileh)
;~ 	EndFunc   ;==>_sendmessages
	Func TelegramInitialMessage($UserID)
;~ 	ConsoleWrite('++TelegramInitialMessage() = '& @crlf)
		$message ="SubteBA BOT , lee los informes de Subte BA en Twitter, y los manda por este canal. "
		$message&='Este canal no es official del subte de Buenos Aires Ni de Metrovias.'  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Commandos:'  & $nuevaLinea
		$message&='/INFO -> Muestra este mensage'  & $nuevaLinea
		$message&='/START -> Activa la recepcion de alertas. '  & $nuevaLinea
		$message&='/STOP  -> Desactiva la recepcion de alertas. '  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Futuros Commandos:'  & $nuevaLinea
		$message&='/Solo A  -> Solo recepcion de alertas de la Linea A, B (C, D, E, H, P.'  & $nuevaLinea
		$message&='/P propuesta -> Enviar propuestas'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : $respuestaInitialMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramSTOPMessage($UserID)
		$message ="Los mensajes de alertas han sido deshabilitados" & $nuevaLinea
		$message&='/START -> Para habilitar la recepcion de alertas'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramSTOPMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramSTARTMessage($UserID)
		$message ="Los mensajes de alertas han sido habilitados" & $nuevaLinea
		$message&='/STOP-> Para deshabilitar la recepcion de alertas'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramSTARTMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramErrorMessage($UserID)
		$message ="No se ha registrado el cambio requerido." & $nuevaLinea
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramErrorMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramBaseMessage($UserID)
		$message ="No logro entender el mensaje." & $nuevaLinea
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea
		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramErrorMessage = ' & $respuesta & @crlf )
	EndFunc
	Func ReformatMessage($message)
;~ 	ConsoleWrite('++ReformatMessage() = '& @crlf)
		$msgArr=StringSplit($message,"Actualizado",1)
		$diaHoraArr=stringsplit(StringStripWS($msgArr[2],1+2)," ")
		$hora=$diaHoraArr[2]
		$dia=$diaHoraArr[1]
		$msg=""&$hora&""&"     " & $dia & $nuevaLinea & StringStripWS($msgArr[1],1+2)
		return $msg
	EndFunc
	Func sendmessages($message)
		$message=ReformatMessage($message)
		SQLGetActiveUsers()
		If  IsArray($qryResult) Then
			for $i=1 to UBound($qryResult)-1
				$isDev = $qryResult[$i][4]
				$chatid = $qryResult[$i][0]
				$ChatUser = $qryResult[$i][1] & " " & $qryResult[$i][2]
				if $chatID<>"" then
					select
						Case $SendToAll = 1
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
						Case $isDev = 1 AND $SendToAll = 0
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
					endSelect
					;~ $respuesta  0 is ok
				endif
			next
			return true
		endif
		Return false
	EndFunc   ;==>_sendmessages
	Func SendTelegramexec($chatid,$msgtext="testeo harcoded")
		$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & _
		"&text=" & $msgtext & "&parse_mode=HTML"
		$sGet = HttpGet($urlMSG)

		if $sget<>"0"  then
			ConsoleWrite('Tlgm sent = ' & $msgtext & @crlf )
			return 0
		Else
			$s_text="Error sending message to Telegram = " & $sGet
			ConsoleWrite('!! ' & $s_text & @crlf )
			return 1
		endif
	EndFunc

#endregion
#region  ==== Tweeter scrapping ===================================================================
	func _ScrapTweetMessages($Username)
		Local $sData = InetRead("https://twitter.com/"&$Username)
		Local $nBytesRead = @extended
		ConsoleWrite('@@ BytesRead = ' & $nBytesRead &"   ")
		$htmltxt = BinaryToString($sData)
		If $nBytesRead < 100000 or StringInStr($htmltxt,"subteba")<1 Then
			ConsoleWrite('  Connection issue contacting  ' & "https://twitter.com/"&$Username& @crlf)
			$htmltxt=""
			Return $htmltxt
		endif
		return $htmltxt
	EndFunc
	Func _gettweetArr($htmltxt)
		$MSGArr = StringRegExp($htmltxt, '(?s)(?i)
(.*?)
', 3)
		if IsArray($MSGArr) then
			dim  $TweetMSGArr[UBound($MSGArr)]
			For $i = 0 To UBound($MSGArr) -1
				$TweetMessage = StringRegExp($MSGArr[$i], '(?s)(?i)
(.*?)
', 1)
				$mensaje = clearstring($TweetMessage[1])
				$TweetMSGArr[$i]=$mensaje
			Next
			$TweetDate = StringRegExp($htmltxt, '(?s)(?i)data-time="(.*?)"', 3)
			$TweetIDArr = StringRegExp($htmltxt, '(?s)(?i)data-tweet-id="(.*?)"', 3)
			$TweetArrAux = _mergeArray($TweetIDArr, $TweetMSGArr)
			$TweetArr = _mergeArray($TweetArrAux, $TweetDate)
	;~ 		_ArrayDisplay($TweetArr)
			return $TweetArr
		Else
			ConsoleWrite('!!!(' &  @ScriptLineNumber & ') : Error on  $MSGArr = ' & $MSGArr & @crlf )
			return 0
		endif
	EndFunc
#endregion
#region  ==== Bot Messages handeling ===================================================================
	Func Get_BotOffSet()
;~ 		ConsoleWrite('++Get_BotOffSet() = '& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 1.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,0)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 2.' & $OffsetFile )
			return 0
		endif
		Local $offset = FileReadLine($fileh)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("Get OffSet:"& $offset)
		FileClose($fileh)
		return $offset
	EndFunc
	Func Set_BotOffSet($offset)
;~ 		ConsoleWrite('++Set_BotOffSet() = '&$offset& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 3.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,2)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 4.' & $OffsetFile )
			return 0
		endif
		FileWriteLine($fileh,$offset)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("    Set OffSet:"& $offset &@crlf)
		FileClose($fileh)
		return 1
	EndFunc
	func UpdateUsers()
		ConsoleWrite('  '&@HOUR & ':' & @MIN&'  Update users.  ' )
		local $s=GetBotUpdates()
		if $s then
			$s=ParseForUserUpdate($s)
			if $s then
				$oJSON = _OO_JSON_Init()
				$jsonObj = $oJSON.parse($s)
				if $jsonObj.ok  then
					if $jsonObj.jsonPath( "$.result").stringify() = "[[]]" then
						ConsoleWrite(' No Bot data ' & @crlf)
					Else
						ConsoleWrite('  Updating... ' & @crlf)
						$UpdateIDArr = StripIntJS($jsonObj.jsonPath( "$.result..update_id").stringify()  )
						$UserIDArr =   StripIntJS($jsonObj.jsonPath( "$.result..message.from.id").stringify())
						$FnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.first_name").stringify())
						$LnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.last_name").stringify())
						$epochArr =    StripIntJS($jsonObj.jsonPath( "$.result..message.date").stringify())
						$menssageArr = StripStrJS($jsonObj.jsonPath( "$.result..message.text").stringify())
						if  $UserIDArr[0] = $UpdateIDArr[0] AND $UserIDArr[0] = $FnameArr[0] AND $UserIDArr[0] = $LnameArr[0]  AND $UserIDArr[0] = $epochArr[0]  AND $UserIDArr[0] = $menssageArr[0] then
							$retBad=0
							for $i=1 to $UserIDArr[0]
								$ret=SQLregister($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i],$menssageArr[$i])
								$ret1=ParseBotMessage()
								ConsoleWrite('@@(' & @ScriptLineNumber & ') : $ret1 = ' & $ret1 & @crlf )
								if (Not $ret) or (Not $ret1)  then	$retBad+=1
								$UpdateID=$UpdateIDArr[$i]
							next
							if $retBad=0 then Set_BotOffSet($UpdateID+1)
						Else
							_printFromArray($UserIDArr)
							_printFromArray($FnameArr)
							_printFromArray($LnameArr)
							_printFromArray($epochArr)
							_printFromArray($menssageArr)
							ConsoleWrite('  Error in JS array . exiting..... ' & @crlf)
							exit 29
						endif
					endif
				endif
			endif
		endif
	EndFunc
	Func GetBotUpdates()
		$offset=Get_BotOffSet()
		$urlMSG="https://api.telegram.org/" & $token & "/getUpdates?offset="&$offset
		$sGet = HttpGetJson1($urlMSG)
		ConsoleWrite('@@ $sGet = ' & $sGet & @crlf )
		if $sGet<>"" then
			return $sGet
		Else
			$s_text="Error getUpdates from Telegram = "
			ConsoleWrite('!! ' & $s_text & @crlf & "! " & $sGet)
			return false
		endif
	EndFunc
	Func StripStrJS($st)
		$st=StringReplace($st,'","',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func StripIntJS($st)
		$st=StringReplace($st,',',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func ParseForUserUpdate($s)
		if StringInStr($s,'"location":') Then
			$s='{"ok":true,"result":[]}'
			return $s
		endif
;~ 		eliminate contact info
		$s=StringRegExpReplace($s,'(?s)(?i)"contact":(.*?)}'  ,  '"text": ""' )
;~ 		replace username last-name
		$s=StringReplace($s,'"username":','"last_name":')
		return $s
	EndFunc
	Func SQLregister($UserID,$Fname,$Lname,$epoch,$mensage)
;~ 	ConsoleWrite('++SQLregister() = '& @crlf)

		$existUser=0
		If SQLExistUser($UserID)=$userID then $existUser=1
		if $existUser=0 then
			$setactive=1
			$ret=SQLInsertUser($UserID,$Fname,$Lname,$epoch,$setactive)
			if $ret then
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			else
				$ret=TelegramErrorMessage($UserID)
				if $ret=0 then return true
			endif
			return false
		endif

		$setactive=-1
		if AIMessage($mensage,"/START") then $setactive=1
		if AIMessage($mensage,"/STOP") then $setactive=0
		if $existUser=1 AND $setactive<>-1 then
			$ret=SQLUpdateUserActive($UserID,$Fname,$Lname,$setactive)
			if $ret and $setactive=0 then
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			endif
			if $ret and $setactive=1 then
				$ret=TelegramSTARTMessage($UserID)
				if $ret=0 then return true
			endif
			if NOT $ret then TelegramErrorMessage($UserID)
			return false
		endif

		return true
	EndFunc
	Func SQLInsertUser($UserID,$Fname,$Lname,$epoch,$active=1)
		ConsoleWrite('  Nuevo usuario = '& $Fname & "  "  & $Lname  & @crlf)
		$query='INSERT INTO Users VALUES (' & $UserID & ',"' & $Fname & '","' & $Lname & '",' & $active &',0,' & $epoch & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting User ErrNo 1011" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLUpdateUserActive($UserID,$Fname,$Lname,$active=1)
		ConsoleWrite('    Usuario Activo 1/Start 0/Stop= '&$active& "  " & $Fname & "  "  & $Lname  & @crlf)
		$query='UPDATE  Users SET Active=' & $active &' WHERE UserID='& $UserID & ' ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			ConsoleWrite("       Error updating active user User ErrNo 1012" & @CRLF & $query& @crlf)
			Return false
		EndIf
	EndFunc
	Func SQLExistUser($UserID)
;~ 	ConsoleWrite('++SQLExistUser() = '& @crlf)
		$query='SELECT UserID FROM Users WHERE UserID="'&$UserID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
#endregion
#region   ===========================================================================
	func closeall()
		_SQLite_Close()
		_SQLite_Shutdown()
		exit 30
	EndFunc
#endregion
#region =====================================   Helpers functions  ===============================
	Func _mergeArray($array1, $array2)
		$array1 = _ArrayAdd_Column($array1)
		$size = UBound($array1)
		$newCol = UBound($array1, 2) - 1
		For $i = 0 To $size - 1
			$array1[$i][$newCol] = $array2[$i]
		Next
	;~   _ArrayDisplay($array1)
		Return $array1
	EndFunc   ;==>_mergeArray
	Func _ArrayAdd_Column($Array)
		Local $aTemp[UBound($Array)][UBound($Array, 0) + 1]
		For $i = 0 To UBound($Array) - 1

			For $j = 0 To UBound($Array, 0) - 1
				If UBound($Array, 0) = 1 Then $aTemp[$i][0] = $Array[$i]
				If UBound($Array, 0) > 1 Then $aTemp[$i][$j] = $Array[$i][$j]
			Next
		Next
		Return $aTemp
	EndFunc   ;==>_ArrayAdd_Column
	Func _ClearSciteConsole()
		ConsoleWrite('!!!!!!!!!!!_ClearSciteConsole Func General 92!!!!!!!!!!!!  ' & @CRLF)
		ControlSend("[CLASS:SciTEWindow]", "", "Scintilla2", "+{F5}")
	EndFunc   ;==>_ClearSciteConsole
	Func _GetDOSOutput($sCommand)
	 ConsoleWrite('++_GetDOSOutput $sCommand = ' & $sCommand & @crlf )
		Local $iPID, $sOutput = ""
		$iPID = Run('"' & @ComSpec & '" /c ' & $sCommand, "", @SW_HIDE, 2 + 4)
		While 1
			$sOutput &= StdoutRead($iPID, False, False)
			$err=@error
			If $err Then
				ConsoleWrite('!!  _GetDOSOutput $err = ' & $err & @crlf )
				ExitLoop
			EndIf
	;~ 	Sleep(10)
		WEnd
		ConsoleWrite('>> 	Output = ' & $sOutput & @crlf )
		Return $sOutput
	EndFunc   ;==>_GetDOSOutput
	Func _timeBetween($cTime, $sTime, $eTime)
		 If Not _DateIsValid('2000/01/01 ' & $cTime) Then Return -1
		 If Not _DateIsValid('2000/01/01 ' & $sTime) Then Return -2
		 If Not _DateIsValid('2000/01/01 ' & $eTime) Then Return -3
		 ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') & @CRLF)
		 ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') & @CRLF)
		 If _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') < 0 And _
			 _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') > 0 Then
			  Return 1
		 Else
			  Return 0
		 EndIf
	EndFunc  ; ==>_timeBetween
#endregion

#region ====INIT ===============================================================
	Func _ConfigInitial()
;~ 		ConsoleWrite('++ConfigDBInitial() = ' & @CRLF)
		_SQLite_down()
;~ 		_DBvarInit()
		; -------check if SQLIte SubteBA db exist
		SQLite_init()
		$SQLq = "SELECT name FROM sqlite_temp_master WHERE type='table';"
		_SQLITErun($SQLq, $dbfile, $quietSQLQuery)
	;~ 	;-------- Init Log
	;~ 	_initLog()
		;------------------------------------------------------------------------------
	EndFunc   ;==>_ConfigDBInitial
#endregion
#region  ==== SQL functions =======================================================================
	Func SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
;~ 		ConsoleWrite('++InsertMessageSQL() = '& @crlf)
		$query='INSERT INTO messages VALUES (' & $TweetID & ',"' & $TweeMsg & '" ,' & $TweeDate & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting mesages ErrNo 1010" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLGetUsers()
;~ 		ConsoleWrite('++SQLGetUsers() = '& @crlf)
		$query='SELECT * FROM Users ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetActiveUsers()
;~ 		ConsoleWrite('++SQLGetActiveUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetDevUsers()
;~ 		ConsoleWrite('++SQLGetDevUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 AND Dev=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLExist_Message($TweetID)
;~ 		ConsoleWrite('++Exist_Message() = '&$TweetID& @crlf)
		$query='SELECT id FROM messages WHERE id="'&$TweetID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
#endregion
#region  ==== send messages =======================================================================
;~  	Func sendmessages($message)  ;~ from file of recipients
;~ 		Local $fileh = FileOpen("secret\recipients.txt", 0)
;~ 		If $fileh = -1 Then
;~ 			Exit 26
;~ 		EndIf
;~ 		While 1
;~ 			Local $chatidLine = FileReadLine($fileh)
;~ 			If @error = -1 Then ExitLoop
;~ 			$chatidArr = StringSplit($chatidLine, ',')
;~ 			$chatid = $chatidArr[1]
;~ 			if $chatID<>"" then
;~ 				ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $chatidArr[2] & @CRLF)
;~ 				$respuesta = SendTelegramexec($chatid,$message)
;~ 			$respuesta  0 is ok
;~ 			endif
;~ 		WEnd
;~ 		FileClose($fileh)
;~ 	EndFunc   ;==>_sendmessages
	Func TelegramInitialMessage($UserID)
;~ 	ConsoleWrite('++TelegramInitialMessage() = '& @crlf)
		$message ="SubteBA BOT , lee los informes de Subte BA en Twitter, y los manda por este canal. "
		$message&='Este canal no es official del subte de Buenos Aires Ni de Metrovias.'  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Commandos:'  & $nuevaLinea
		$message&='/INFO -> Muestra este mensage'  & $nuevaLinea
		$message&='/START -> Activa la recepcion de alertas. '  & $nuevaLinea
		$message&='/STOP  -> Desactiva la recepcion de alertas. '  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Futuros Commandos:'  & $nuevaLinea
		$message&='/Solo A  -> Solo recepcion de alertas de la Linea A, B (C, D, E, H, P.'  & $nuevaLinea
		$message&='/P propuesta -> Enviar propuestas'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : $respuestaInitialMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramSTOPMessage($UserID)
		$message ="Los mensajes de alertas han sido deshabilitados" & $nuevaLinea
		$message&='/START -> Para habilitar la recepcion de alertas'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramSTOPMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramSTARTMessage($UserID)
		$message ="Los mensajes de alertas han sido deshabilitados" & $nuevaLinea
		$message&='/STOP-> Para deshabilitar la recepcion de alertas'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramSTARTMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramErrorMessage($UserID)
		$message ="No se ha registrado el cambio requerido." & $nuevaLinea
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramErrorMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramBaseMessage($UserID)
		$message ="No logro entender el mensaje." & $nuevaLinea
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea
		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramErrorMessage = ' & $respuesta & @crlf )
	EndFunc
	Func ReformatMessage($message)
;~ 	ConsoleWrite('++ReformatMessage() = '& @crlf)
		$msgArr=StringSplit($message,"Actualizado",1)
		$diaHoraArr=stringsplit(StringStripWS($msgArr[2],1+2)," ")
		$hora=$diaHoraArr[2]
		$dia=$diaHoraArr[1]
		$msg=""&$hora&""&"     " & $dia & $nuevaLinea & StringStripWS($msgArr[1],1+2)
		return $msg
	EndFunc
	Func sendmessages($message)
		$message=ReformatMessage($message)
		SQLGetActiveUsers()
		If  IsArray($qryResult) Then
			for $i=1 to UBound($qryResult)-1
				$isDev = $qryResult[$i][4]
				$chatid = $qryResult[$i][0]
				$ChatUser = $qryResult[$i][1] & " " & $qryResult[$i][2]
				if $chatID<>"" then
					select
						Case $SendToAll = 1
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
						Case $isDev = 1 AND $SendToAll = 0
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
					endSelect
					;~ $respuesta  0 is ok
				endif
			next
			return true
		endif
		Return false
	EndFunc   ;==>_sendmessages
	Func SendTelegramexec($chatid,$msgtext="testeo harcoded")
		$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & _
		"&text=" & $msgtext & "&parse_mode=HTML"
		$sGet = HttpGet($urlMSG)

		if $sget<>"0"  then
			ConsoleWrite('Tlgm sent = ' & $msgtext & @crlf )
			return 0
		Else
			$s_text="Error sending message to Telegram = " & $sGet
			ConsoleWrite('!! ' & $s_text & @crlf )
			return 1
		endif
	EndFunc

#endregion
#region  ==== Tweeter scrapping ===================================================================
	func _ScrapTweetMessages($Username)
		Local $sData = InetRead("https://twitter.com/"&$Username)
		Local $nBytesRead = @extended
		ConsoleWrite('@@ BytesRead = ' & $nBytesRead &"   ")
		$htmltxt = BinaryToString($sData)
		If $nBytesRead < 100000 or StringInStr($htmltxt,"subteba")<1 Then
			ConsoleWrite('  Connection issue contacting  ' & "https://twitter.com/"&$Username& @crlf)
			$htmltxt=""
			Return $htmltxt
		endif
		return $htmltxt
	EndFunc
	Func _gettweetArr($htmltxt)
		$MSGArr = StringRegExp($htmltxt, '(?s)(?i)
(.*?)
', 3)
		if IsArray($MSGArr) then
			dim  $TweetMSGArr[UBound($MSGArr)]
			For $i = 0 To UBound($MSGArr) -1
				$TweetMessage = StringRegExp($MSGArr[$i], '(?s)(?i)
(.*?)
', 1)
				$mensaje = clearstring($TweetMessage[1])
				$TweetMSGArr[$i]=$mensaje
			Next
			$TweetDate = StringRegExp($htmltxt, '(?s)(?i)data-time="(.*?)"', 3)
			$TweetIDArr = StringRegExp($htmltxt, '(?s)(?i)data-tweet-id="(.*?)"', 3)
			$TweetArrAux = _mergeArray($TweetIDArr, $TweetMSGArr)
			$TweetArr = _mergeArray($TweetArrAux, $TweetDate)
	;~ 		_ArrayDisplay($TweetArr)
			return $TweetArr
		Else
			ConsoleWrite('!!!(' &  @ScriptLineNumber & ') : Error on  $MSGArr = ' & $MSGArr & @crlf )
			return 0
		endif
	EndFunc
#endregion
#region  ==== Bot Messages handeling ===================================================================
	Func Get_BotOffSet()
;~ 		ConsoleWrite('++Get_BotOffSet() = '& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 1.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,0)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 2.' & $OffsetFile )
			return 0
		endif
		Local $offset = FileReadLine($fileh)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("Get OffSet:"& $offset)
		FileClose($fileh)
		return $offset
	EndFunc
	Func Set_BotOffSet($offset)
;~ 		ConsoleWrite('++Set_BotOffSet() = '&$offset& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 3.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,2)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 4.' & $OffsetFile )
			return 0
		endif
		FileWriteLine($fileh,$offset)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("    Set OffSet:"& $offset &@crlf)
		FileClose($fileh)
		return 1
	EndFunc
	func UpdateUsers()
		ConsoleWrite('  '&@HOUR & ':' & @MIN&'  Update users.  ' )
		local $s=GetBotUpdates()
		if $s then
			$s=ParseForUserUpdate($s)
			if $s then
				$oJSON = _OO_JSON_Init()
				$jsonObj = $oJSON.parse($s)
				if $jsonObj.ok  then
					if $jsonObj.jsonPath( "$.result").stringify() = "[[]]" then
						ConsoleWrite(' No Bot data ' & @crlf)
					Else
						ConsoleWrite('  Updating... ' & @crlf)
						$UpdateIDArr = StripIntJS($jsonObj.jsonPath( "$.result..update_id").stringify()  )
						$UserIDArr =   StripIntJS($jsonObj.jsonPath( "$.result..message.from.id").stringify())
						$FnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.first_name").stringify())
						$LnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.last_name").stringify())
						$epochArr =    StripIntJS($jsonObj.jsonPath( "$.result..message.date").stringify())
						$menssageArr = StripStrJS($jsonObj.jsonPath( "$.result..message.text").stringify())
						if  $UserIDArr[0] = $UpdateIDArr[0] AND $UserIDArr[0] = $FnameArr[0] AND $UserIDArr[0] = $LnameArr[0]  AND $UserIDArr[0] = $epochArr[0]  AND $UserIDArr[0] = $menssageArr[0] then
							$retBad=0
							for $i=1 to $UserIDArr[0]
								$ret=SQLregister($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i],$menssageArr[$i])
								$ret1=ParseBotMessage()
								ConsoleWrite('@@(' & @ScriptLineNumber & ') : $ret1 = ' & $ret1 & @crlf )
								if (Not $ret) or (Not $ret1)  then	$retBad+=1
								$UpdateID=$UpdateIDArr[$i]
							next
							if $retBad=0 then Set_BotOffSet($UpdateID+1)
						Else
							_printFromArray($UserIDArr)
							_printFromArray($FnameArr)
							_printFromArray($LnameArr)
							_printFromArray($epochArr)
							_printFromArray($menssageArr)
							ConsoleWrite('  Error in JS array . exiting..... ' & @crlf)
							exit 29
						endif
					endif
				endif
			endif
		endif
	EndFunc
	Func GetBotUpdates()
		$offset=Get_BotOffSet()
		$urlMSG="https://api.telegram.org/" & $token & "/getUpdates?offset="&$offset
		$sGet = HttpGetJson1($urlMSG)
		ConsoleWrite('@@ $sGet = ' & $sGet & @crlf )
		if $sGet<>"" then
			return $sGet
		Else
			$s_text="Error getUpdates from Telegram = "
			ConsoleWrite('!! ' & $s_text & @crlf & "! " & $sGet)
			return false
		endif
	EndFunc
	Func StripStrJS($st)
		$st=StringReplace($st,'","',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func StripIntJS($st)
		$st=StringReplace($st,',',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func ParseForUserUpdate($s)
		if StringInStr($s,'"location":') Then
			$s='{"ok":true,"result":[]}'
			return $s
		endif
;~ 		eliminate contact info
		$s=StringRegExpReplace($s,'(?s)(?i)"contact":(.*?)}'  ,  '"text": ""' )
;~ 		replace username last-name
		$s=StringReplace($s,'"username":','"last_name":')
		return $s
	EndFunc
	Func SQLregister($UserID,$Fname,$Lname,$epoch,$mensage)
;~ 	ConsoleWrite('++SQLregister() = '& @crlf)

		$existUser=0
		If SQLExistUser($UserID)=$userID then $existUser=1
		if $existUser=0 then
			$setactive=1
			$ret=SQLInsertUser($UserID,$Fname,$Lname,$epoch,$setactive)
			if $ret then
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			else
				$ret=TelegramErrorMessage($UserID)
				if $ret=0 then return true
			endif
			return false
		endif

		$setactive=-1
		if AIMessage($mensage,"/START") then $setactive=1
		if AIMessage($mensage,"/STOP") then $setactive=0
		if $existUser=1 AND $setactive<>-1 then
			$ret=SQLUpdateUserActive($UserID,$Fname,$Lname,$setactive)
			if $ret and $setactive=0 then
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			endif
			if $ret and $setactive=1 then
				$ret=TelegramSTARTMessage($UserID)
				if $ret=0 then return true
			endif
			if NOT $ret then TelegramErrorMessage($UserID)
			return false
		endif

		return true
	EndFunc
	Func SQLInsertUser($UserID,$Fname,$Lname,$epoch,$active=1)
		ConsoleWrite('  Nuevo usuario = '& $Fname & "  "  & $Lname  & @crlf)
		$query='INSERT INTO Users VALUES (' & $UserID & ',"' & $Fname & '","' & $Lname & '",' & $active &',0,' & $epoch & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting User ErrNo 1011" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLUpdateUserActive($UserID,$Fname,$Lname,$active=1)
		ConsoleWrite('    Usuario Activo 1/Start 0/Stop= '&$active& "  " & $Fname & "  "  & $Lname  & @crlf)
		$query='UPDATE  Users SET Active=' & $active &' WHERE UserID='& $UserID & ' ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			ConsoleWrite("       Error updating active user User ErrNo 1012" & @CRLF & $query& @crlf)
			Return false
		EndIf
	EndFunc
	Func SQLExistUser($UserID)
;~ 	ConsoleWrite('++SQLExistUser() = '& @crlf)
		$query='SELECT UserID FROM Users WHERE UserID="'&$UserID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
#endregion
#region   ===========================================================================
	func closeall()
		_SQLite_Close()
		_SQLite_Shutdown()
		exit 30
	EndFunc
#endregion
#region =====================================   Helpers functions  ===============================
	Func _mergeArray($array1, $array2)
		$array1 = _ArrayAdd_Column($array1)
		$size = UBound($array1)
		$newCol = UBound($array1, 2) - 1
		For $i = 0 To $size - 1
			$array1[$i][$newCol] = $array2[$i]
		Next
	;~   _ArrayDisplay($array1)
		Return $array1
	EndFunc   ;==>_mergeArray
	Func _ArrayAdd_Column($Array)
		Local $aTemp[UBound($Array)][UBound($Array, 0) + 1]
		For $i = 0 To UBound($Array) - 1

			For $j = 0 To UBound($Array, 0) - 1
				If UBound($Array, 0) = 1 Then $aTemp[$i][0] = $Array[$i]
				If UBound($Array, 0) > 1 Then $aTemp[$i][$j] = $Array[$i][$j]
			Next
		Next
		Return $aTemp
	EndFunc   ;==>_ArrayAdd_Column
	Func _ClearSciteConsole()
		ConsoleWrite('!!!!!!!!!!!_ClearSciteConsole Func General 92!!!!!!!!!!!!  ' & @CRLF)
		ControlSend("[CLASS:SciTEWindow]", "", "Scintilla2", "+{F5}")
	EndFunc   ;==>_ClearSciteConsole
	Func _GetDOSOutput($sCommand)
	 ConsoleWrite('++_GetDOSOutput $sCommand = ' & $sCommand & @crlf )
		Local $iPID, $sOutput = ""
		$iPID = Run('"' & @ComSpec & '" /c ' & $sCommand, "", @SW_HIDE, 2 + 4)
		While 1
			$sOutput &= StdoutRead($iPID, False, False)
			$err=@error
			If $err Then
				ConsoleWrite('!!  _GetDOSOutput $err = ' & $err & @crlf )
				ExitLoop
			EndIf
	;~ 	Sleep(10)
		WEnd
		ConsoleWrite('>> 	Output = ' & $sOutput & @crlf )
		Return $sOutput
	EndFunc   ;==>_GetDOSOutput
	Func _timeBetween($cTime, $sTime, $eTime)
		 If Not _DateIsValid('2000/01/01 ' & $cTime) Then Return -1
		 If Not _DateIsValid('2000/01/01 ' & $sTime) Then Return -2
		 If Not _DateIsValid('2000/01/01 ' & $eTime) Then Return -3
		 ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') & @CRLF)
		 ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') & @CRLF)
		 If _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') < 0 And _
			 _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') > 0 Then
			  Return 1
		 Else
			  Return 0
		 EndIf
	EndFunc  ; ==>_timeBetween
#endregion


AutoIt function update

AutoIt function update

Fixes atomizer/muledump#50

#include <String.au3>
#include <File.au3>
#include <Array.au3>

Global $string, $password, $email, $data, $path, $search, $file, $root
$root = "HKEY_CLASSES_ROOT\muledump"

Func _write()
	RegWrite($root,"","REG_SZ","URL: muledump Protocol")
	RegWrite($root,"URL Protocol","REG_SZ","")
	RegWrite($root & "\shell")
	RegWrite($root & "\shell\open")
	RegWrite($root & "\shell\open\command","","REG_SZ", @AutoItExe & ' "' & @ScriptFullPath & '" %1')
	If RegRead("HKEY_CLASSES_ROOT\muledump","") Then
		MsgBox(64,"mulelogin","muledump: URL handler installed")
	Else
		MsgBox(16,"mulelogin","Unable to write to registry" & @CRLF & "Try again with admin rights")
	EndIf
	Exit
EndFunc

Func _install()
	Local $k
	$k = RegEnumKey($root, 1)
	If @error == 2 Then
		MsgBox(16,"mulelogin","Unable to open the registry" & @CRLF & "Try again with admin rights")
		Exit
	EndIf
	If @error == 1 Then _write()
	$k = MsgBox(6 + 32, 'mulelogin', _
		'URL handler is already installed. Uninstall?' & @CRLF & @CRLF & _
		'"Cancel" to do nothing' & @CRLF & _
		'"Try Again" to reinstall' & @CRLF & _
		'"Continue" to uninstall')
	If $k == 10 Then _write()
	If $k == 11 Then
		RegDelete($root)
		if @error <> 0 Then
			MsgBox(16,"mulelogin","Unable to delete the key" & @CRLF & "Try again with admin rights")
		Else
			MsgBox(64,"mulelogin","muledump: URL handler uninstalled")
		EndIf
	EndIf
	Exit
EndFunc

Func _length($string)
	Local $binlength, $declength, $array, $result
	$declength = StringLen($string)/2
    While $declength > 0
        $binlength &= Mod($declength,2)
        $declength = Floor($declength/2)
    WEnd
	$binlength = StringReverse($binlength)
	$binlength = $binlength & "1"
	$array = StringSplit($binlength,"")
	For $i = 1 To $array[0]
        $array[0] -= 1
        If $array[$i] = "1" Then $result += 2 ^ ($array[0])
	Next
	Return Hex(Int($result),2)
EndFunc

Func _build()
	;header
	$string  = "0x 00 BF" 						;Magic Number		 2 bytes
	$string &= "?? ?? ?? ??"					;Size				 4 bytes
	$string &= "54 43 53 4F 00 04 00 00 00 00"	;Marker				10 bytes
	$string &= "00 05"							;Name Size			 2 bytes
	$string &= "52 6F 74 4D 47"					;"RotMG"			 5 bytes
	$string &= "00 00 00"						;Padding			 3 bytes
	$string &= "03"								;AMF Version		 1 byte

	;data
	$string &= "11"								;Length				 1 byte
	$string &= "50 61 73 73 77 6F 72 64"		;"Password"			 8 bytes
	$string &= "06"								;Type (string) 		 1 byte
	$string &= _length($password)				;Length				 1 byte
	$string &= $password						;Actual Password	 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string &= "09"								;Length				 1 byte
	$string &= "47 55 49 44"					;"GUID"				 4 bytes
	$string &= "06"								;Type (string)		 1 byte
	$string &= _length($email)					;Length				 1 byte
	$string &=  $email							;Email				 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string = StringReplace($string," ","")
	$string = StringRegExpReplace($string,"\?{8}",Hex(Int(StringLen(StringMid($string,15))/2)))
EndFunc

If $CmdLine[0] = 0 Then _install()

$data = StringReplace($CmdLine[1],"muledump:","")
$data = StringSplit($data,"-")
$email = $data[1]
$password = $data[2]

_build()

$path = @AppDataDir & "\Macromedia\Flash Player\#SharedObjects\"
$search = FileFindFirstFile($path & "*")
$path &= FileFindNextFile($search) & "\www.realmofthemadgod.com\RotMG.sol"
FileClose($search)
$file = FileOpen($path,18)
FileWrite($file,$string)
FileClose($file)

ShellExecute("http://www.realmofthemadgod.com/")
; replace the line above if you're using a projector
; for example, with totalcmd + swfview
;ShellExecute('C:\Program Files\Total Commander\Totalcmd.exe', '/S=L:Pswfview e:\temp\rotmg\loader.swf')

#include <String.au3>
#include <File.au3>
#include <Array.au3>

Global $string, $password, $email, $data, $path, $search, $file, $root
$root = "HKEY_CLASSES_ROOT\muledump"

Func _write()
	RegWrite($root,"","REG_SZ","URL: muledump Protocol")
	RegWrite($root,"URL Protocol","REG_SZ","")
	RegWrite($root & "\shell")
	RegWrite($root & "\shell\open")
	RegWrite($root & "\shell\open\command","","REG_SZ", @AutoItExe & ' "' & @ScriptFullPath & '" %1')
	If RegRead("HKEY_CLASSES_ROOT\muledump","") Then
		MsgBox(64,"mulelogin","muledump: URL handler installed")
	Else
		MsgBox(16,"mulelogin","Unable to write to registry" & @CRLF & "Try again with admin rights")
	EndIf
	Exit
EndFunc

Func _install()
	Local $k
	$k = RegEnumKey($root, 1)
	If @error == 2 Then
		MsgBox(16,"mulelogin","Unable to open the registry" & @CRLF & "Try again with admin rights")
		Exit
	EndIf
	If @error == 1 Then _write()
	$k = MsgBox(6 + 32, 'mulelogin', _
		'URL handler is already installed. Uninstall?' & @CRLF & @CRLF & _
		'"Cancel" to do nothing' & @CRLF & _
		'"Try Again" to reinstall' & @CRLF & _
		'"Continue" to uninstall')
	If $k == 10 Then _write()
	If $k == 11 Then
		RegDelete($root)
		if @error <> 0 Then
			MsgBox(16,"mulelogin","Unable to delete the key" & @CRLF & "Try again with admin rights")
		Else
			MsgBox(64,"mulelogin","muledump: URL handler uninstalled")
		EndIf
	EndIf
	Exit
EndFunc

Func _length($string)
	Local $binlength, $declength, $array, $result
	$declength = StringLen($string)/2
    While $declength > 0
        $binlength &= Mod($declength,2)
        $declength = Floor($declength/2)
    WEnd
	$binlength = _StringReverse($binlength)
	$binlength = $binlength & "1"
	$array = StringSplit($binlength,"")
	For $i = 1 To $array[0]
        $array[0] -= 1
        If $array[$i] = "1" Then $result += 2 ^ ($array[0])
	Next
	Return Hex(Int($result),2)
EndFunc

Func _build()
	;header
	$string  = "0x 00 BF" 						;Magic Number		 2 bytes
	$string &= "?? ?? ?? ??"					;Size				 4 bytes
	$string &= "54 43 53 4F 00 04 00 00 00 00"	;Marker				10 bytes
	$string &= "00 05"							;Name Size			 2 bytes
	$string &= "52 6F 74 4D 47"					;"RotMG"			 5 bytes
	$string &= "00 00 00"						;Padding			 3 bytes
	$string &= "03"								;AMF Version		 1 byte

	;data
	$string &= "11"								;Length				 1 byte
	$string &= "50 61 73 73 77 6F 72 64"		;"Password"			 8 bytes
	$string &= "06"								;Type (string) 		 1 byte
	$string &= _length($password)				;Length				 1 byte
	$string &= $password						;Actual Password	 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string &= "09"								;Length				 1 byte
	$string &= "47 55 49 44"					;"GUID"				 4 bytes
	$string &= "06"								;Type (string)		 1 byte
	$string &= _length($email)					;Length				 1 byte
	$string &=  $email							;Email				 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string = StringReplace($string," ","")
	$string = StringRegExpReplace($string,"\?{8}",Hex(Int(StringLen(StringMid($string,15))/2)))
EndFunc

If $CmdLine[0] = 0 Then _install()

$data = StringReplace($CmdLine[1],"muledump:","")
$data = StringSplit($data,"-")
$email = $data[1]
$password = $data[2]

_build()

$path = @AppDataDir & "\Macromedia\Flash Player\#SharedObjects\"
$search = FileFindFirstFile($path & "*")
$path &= FileFindNextFile($search) & "\www.realmofthemadgod.com\RotMG.sol"
FileClose($search)
$file = FileOpen($path,18)
FileWrite($file,$string)
FileClose($file)

ShellExecute("http://www.realmofthemadgod.com/")
; replace the line above if you're using a projector
; for example, with totalcmd + swfview
;ShellExecute('C:\Program Files\Total Commander\Totalcmd.exe', '/S=L:Pswfview e:\temp\rotmg\loader.swf')


Update mancala.au3

Update mancala.au3

;~ #AutoIt3Wrapper_AU3Check_Parameters= -q -d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
;~ #Tidy_Parameters=/sf

; #SCRIPT# ======================================================================================================================
; Name ..........: mancala.au3
; Author ........: Luigi (Luismar Chechelaky)
; Description ...: adaptação do jogo de mancala para AutoIt
; Link ..........: https://github.com/chechelaky/AutoIt/blob/master/mancala/mancala.au3
; webgrafia......: https://pt.wikipedia.org/wiki/Mancala
;                  http://www.colegioglauciacosta.com.br/moodle/file.php/1/Regras_Awele_CLMasse.pdf
;                  http://www.math.ku.dk/famos/.arkiv/22-1/kalaha.pdf
;                  http://fritzdooley.com/mancala/4_computer-aided_game_strategy_reverse_induction.html
; Todo...........: implementar a verificação do vencedor
; ===============================================================================================================================

#include-once
#include <Array.au3>
#include <GUIConstantsEx.au3>
#include <Array.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#include <ColorConstants.au3>
#include <String.au3>

Global $DEFAULT = 0xD4D4D4, $GREEN = 0x00FF00, $ORANGE = 0xFF9900

OnAutoItExitRegister("OnExit")

Opt("GUIOnEventMode", 1)
Opt("GUIEventOptions", 1)
Opt("MustDeclareVars", 1)

; [ handle, id, is_kala, player ]
Global $JOGA_DE_NOVO = False
Global $ARR[14][7]
Global $aGuiSize[2] = [800, 600]
Global $sGuiTitle = "GuiTitle"
Global $hGui
Global $DUMMY
Global $RESET
Global $WHO_PLAY, $AUTOMATIC = False
Global $FIRST = 0
Global $hQuemJoga

$hGui = GUICreate($sGuiTitle, $aGuiSize[0], $aGuiSize[1], 1366 - 800, 0)
GUISetOnEvent($GUI_EVENT_CLOSE, "Quit")
$DUMMY = GUICtrlCreateInput("", 0, 0, 1, 1)
$RESET = GUICtrlCreateButton("RESET", 10, 200, 80, 25)
GUICtrlSetOnEvent($RESET, "Reset")
$hQuemJoga = GUICtrlCreateButton("", 10, 240, 80, 25)
GUICtrlSetOnEvent($hQuemJoga, "QuemJoga")
Botoes()
GUISetState(@SW_SHOW, $hGui)

While Sleep(25)
WEnd

Func OnExit()
	GUISetState($hGui, @SW_HIDE)
	GUIDelete($hGui)
EndFunc   ;==>OnExit

Func Quit()
	Exit
EndFunc   ;==>Quit

Func Botoes()
	Local $iIntervalo = 20, $half = $iIntervalo / 2
	Local $iLargura = Int(($aGuiSize[0] - $iIntervalo * 9) / 8)

	For $ii = 0 To 13
		Switch $ii
			Case 0 To 5
				$ARR[$ii][0] = Input(4, $iIntervalo + ($iIntervalo + $iLargura) * ($ii + 1), $iIntervalo * 2 + $iLargura, $iLargura, $iLargura, "Evento", $SS_SUNKEN + $SS_CENTER)
				$ARR[$ii][1] = $ii
				$ARR[$ii][2] = 0
				$ARR[$ii][3] = 1
				$ARR[$ii][4] = 12 - $ii
				$ARR[$ii][5] = 6
			Case 6
				$ARR[$ii][0] = Input(0, $iIntervalo * 8 + $iLargura * 7, $iIntervalo, $iLargura, $iLargura * 2 + $iIntervalo, 0, $SS_SUNKEN + $SS_CENTER + $SS_CENTERIMAGE)
				$ARR[$ii][1] = $ii
				$ARR[$ii][2] = 1
				$ARR[$ii][3] = 1
				$ARR[$ii][4] = -1
				$ARR[$ii][5] = 6
			Case 13
				$ARR[$ii][0] = Input(0, $iIntervalo, $iIntervalo, $iLargura, $iLargura * 2 + $iIntervalo, 0, $SS_SUNKEN + $SS_CENTER + $SS_CENTERIMAGE)
				$ARR[$ii][1] = $ii
				$ARR[$ii][2] = 1
				$ARR[$ii][3] = 2
				$ARR[$ii][4] = -1
				$ARR[$ii][5] = 13
			Case 7 To 12
				$ARR[$ii][0] = Input(4, $iIntervalo + ($iIntervalo + $iLargura) * (13 - $ii), $iIntervalo, $iLargura, $iLargura, "Evento", $SS_SUNKEN + $SS_CENTER)
				$ARR[$ii][1] = $ii
				$ARR[$ii][2] = 0
				$ARR[$ii][3] = 2
				$ARR[$ii][4] = 12 - $ii
				$ARR[$ii][5] = 13
		EndSwitch
		GUICtrlSetBkColor($ARR[$ii][0], 0xD4D4D4)
		GUICtrlSetTip($ARR[$ii][0], $ARR[$ii][0], "$ii[" & $ii & "]" & @CRLF & "contra[" & $ARR[$ii][4] & "]")
		GUICtrlSetFont($ARR[$ii][0], 40, 400, 0, "Courier New")
	Next
EndFunc   ;==>Botoes

Func _Reset()
	For $ii = 0 To 13
		GUICtrlSetBkColor($ARR[$ii][0], $DEFAULT)
		$ARR[$ii][6] = 0
	Next
EndFunc   ;==>_Reset

Func QuemJoga()

EndFunc   ;==>QuemJoga

Func CorDefault()
	For $ii = 0 To 13
		GUICtrlSetBkColor($ARR[$ii][0], $DEFAULT)
	Next
EndFunc   ;==>CorDefault

Func Evento()
	_Reset()
	Local $id = @GUI_CtrlId - $ARR[0][0]
	Local $MY_KALA = $ARR[$ARR[$id][5]][0]
	$JOGA_DE_NOVO = False
	Local $iPlayer = $ARR[$id][3]
	If Not $FIRST Then $FIRST = $iPlayer

	Local $iPedras = Number(GUICtrlRead(@GUI_CtrlId))
	If Not $iPedras Then Return
	GUICtrlSetData(@GUI_CtrlId, 0)
	While $iPedras
		$id += 1
		If $id > 13 Then $id -= 14
		If Not $ARR[$id][2] Or IsMyKala($id, $iPlayer) Then
			Sleep(100)
			GUICtrlSetData($ARR[$id][0], GUICtrlRead($ARR[$id][0]) + 1)
			GUICtrlSetBkColor($ARR[$id][0], 0xFF9900)
			$iPedras -= 1
			$ARR[$id][6] = $iPlayer
			If Not $iPedras And $ARR[$id][0] = $MY_KALA Then
				$JOGA_DE_NOVO = True
;~ 				ConsoleWrite("$JOGA_DE_NOVO 1" & @LF)
			EndIf
		EndIf
	WEnd
;~ 	_ArrayDump($ARR)
;~ 	ConsoleWrite("id[" & $id & "] a[" & $ARR[$ARR[$id][2]][6] & "] b[" & $iPlayer & "]" & @LF)
	If Not $ARR[$id][2] And Number(GUICtrlRead($ARR[$id][0])) = 1 And Number(GUICtrlRead($ARR[$ARR[$id][4]][0])) And $ARR[$ARR[$id][2]][6] <> $iPlayer Then
;~ 		ConsoleWrite("MANCALA" & @LF)
		GUICtrlSetData($MY_KALA, 1 + GUICtrlRead($ARR[$ARR[$id][4]][0]) + GUICtrlRead($MY_KALA))
		GUICtrlSetData($ARR[$ARR[$id][4]][0], 0)
		GUICtrlSetData($ARR[$id][0], 0)
		$JOGA_DE_NOVO = True
;~ 		ConsoleWrite("$JOGA_DE_NOVO 2" & @LF)
	EndIf

	Local $iTotal = 0

	Local $1 = 0, $2 = 0, $num = 0

	For $ii = 0 To 13
		$num = Number(GUICtrlRead($ARR[$ii][0]))
		$1 += (Not $ARR[$ii][2] And $ARR[$ii][3] = 1) ? $num : 0
		$2 += (Not $ARR[$ii][2] And $ARR[$ii][3] = 2) ? $num : 0
		$iTotal += $num
	Next
	If $iTotal <> 48 Then MsgBox(0, "Erro", "Contagem errada!" & @CRLF & $iTotal)
	If Not $1 Or Not $2 Then
		If $1 > $2 Then
			HouveGanhador(1, $1, $2)
		Else
			HouveGanhador(2, $1, $2)
		EndIf
	EndIf
	GUICtrlSetState($DUMMY, $GUI_FOCUS)
	ConsoleWrite("$JOGA_DE_NOVO[" & ($JOGA_DE_NOVO = True ? "T" : "F")& "] $IP=$FI[" & ($iPlayer = $FIRST ? "T" : "F") & "] $iPlayer[" & $iPlayer & "]" & @LF)

	If $JOGA_DE_NOVO Then
		If $FIRST <> $iPlayer Then AdversarioJoga($iPlayer)
;~ 		AdversarioJoga($iPlayer)
	Else
;~ 		If $FIRST = $iPlayer Then
;~ 			AdversarioJoga($FIRST)
;~ 		Else
;~ 			AdversarioJoga($iPlayer)
;~ 		EndIf
		If $FIRST = $iPlayer Then AdversarioJoga($FIRST = 1 ? 2 : 1)
	EndIf
EndFunc   ;==>Evento

Func AdversarioJoga($player)
;~ 	If $player < 0 Then
;~ 		$player = Abs($player) = 1 ? 2 : 1
;~ 	EndIf
;~ 	ConsoleWrite("AdversarioJoga[" & $player & "]" & @LF)
	Local $move[1]
	For $ii = 0 To 13
		Switch $ii
			Case 6, 13
			Case Else
				If $ARR[$ii][3] = $player And GUICtrlRead($ARR[$ii][0]) Then _ArrayAdd($move, $ARR[$ii][0])
		EndSwitch
	Next
	Local $next = $move[Random(1, UBound($move, 1) - 1)]
	Local $try = ControlClick($hGui, "", $next, "left", 1)
EndFunc   ;==>AdversarioJoga

Func HouveGanhador($ganhador = 0, $1 = 0, $2 = 0)
;~ 	ConsoleWrite("1[" & $1 & "] 2[" & $2 & "]" & @LF)
	For $ii = 0 To 13
		If $ganhador = $ARR[$ii][3] Then
			GUICtrlSetBkColor($ARR[$ii][0], 0x00FF00)
		Else
			GUICtrlSetBkColor($ARR[$ii][0], 0xFF0000)
		EndIf
	Next
;~ 	GUICtrlSetData($ARR[6][0], $1)
;~ 	GUICtrlSetData($ARR[13][0], $2)
EndFunc   ;==>HouveGanhador

Func IsMyKala($id, $iPlayer)
	If $ARR[$id][2] And $ARR[$id][3] = $iPlayer Then Return True
	Return False
EndFunc   ;==>IsMyKala

Func Input($iPedras, $xx, $yy, $ww, $hh, $func = 0, $iStyle = -1)
	If $func Then
		Local $handle = GUICtrlCreateButton($iPedras, $xx, $yy, $ww, $hh, $iStyle)
		GUICtrlSetOnEvent($handle, $func)
	Else
		Local $handle = GUICtrlCreateLabel($iPedras, $xx, $yy, $ww, $hh, $iStyle)
	EndIf
	GUICtrlSetBkColor($handle, $COLOR_SKYBLUE)
	Return $handle
EndFunc   ;==>Input

Func Reset()
	For $ii = 0 To 13
		Switch $ii
			Case 6, 13
				GUICtrlSetData($ARR[$ii][0], 0)
			Case Else
				GUICtrlSetData($ARR[$ii][0], 4)
		EndSwitch
		GUICtrlSetState($ARR[$ii][0], $GUI_ENABLE)
		GUICtrlSetBkColor($ARR[$ii][0], 0xD4D4D4)
	Next
	$FIRST = 0
EndFunc   ;==>Reset

Func _ArrayDump($ARR, $name = "")
	Local $iCol = UBound($ARR, 2)
	Local $aCol[$iCol]
	Local $iLen
	Local $line_head = "+"
	For $ii = 0 To UBound($ARR, 1) - 1
		For $jj = 0 To UBound($ARR, 2) - 1
			$iLen = StringLen($ARR[$ii][$jj])
			If $iLen > $aCol[$jj] Then $aCol[$jj] = $iLen
		Next
	Next
	Local $line = "+"
	For $ii = 0 To $iCol - 1
		$line &= _StringRepeat("-", $aCol[$ii]) & "+"
		$line_head &= _StringRepeat("-", $aCol[$ii] - StringLen(String($ii))) & $ii & "+"
	Next
	If $name Then ConsoleWrite("arr[ " & $name & " ] " & UBound($ARR, 1) & "x" & UBound($ARR, 2) & @LF)
	ConsoleWrite($line_head & @LF)
	For $ii = 0 To UBound($ARR, 1) - 1
		ConsoleWrite($ii = 1 ? $line & @LF & "|" : "|")
		For $jj = 0 To UBound($ARR, 2) - 1
			$iLen = StringLen($ARR[$ii][$jj])
			ConsoleWrite(Conv($ARR[$ii][$jj]) & _StringRepeat(" ", $aCol[$jj] - $iLen) & "|")
		Next
		ConsoleWrite(@LF)
	Next
	ConsoleWrite($line & @LF)
EndFunc   ;==>_ArrayDump

Func Conv($var)
	Local $Pattern[][2] = [["[áãâ]", "a"], ["[éê]", "e"], ["[íî]", "i"], ["[óõô]", "o"], ["[úû]", "u"], ["[ÁÃÂ]", "A"], ["[ÉÊ]", "E"], ["[ÍÎ]", "I"], ["[ÓÕÔ]", "O"], ["[ÚÛ]", "U"], ["[Ç]", "C"], ["[ç]", "c"]]
	For $ii = 0 To UBound($Pattern, 1) - 1
		$var = StringRegExpReplace($var, $Pattern[$ii][0], $Pattern[$ii][1])
	Next
	Return $var
EndFunc   ;==>Conv

#cs
	If $JOGA_DE_NOVO Then
	If $FIRST = $iPlayer Then
	ConsoleWrite(1 & @LF)
	For $ii = 0 To 13
	If Not $ARR[$ii][2] Then
	If $ARR[$ii][3] = $iPlayer Then
	;~ 						GUICtrlSetState($ARR[$ii][0], $GUI_ENABLE)
	GUICtrlSetBkColor($ARR[$ii][0], $GREEN)
	Else
	;~ 						GUICtrlSetState($ARR[$ii][0], $GUI_DISABLE)
	GUICtrlSetBkColor($ARR[$ii][0], $DEFAULT)
	EndIf
	EndIf
	Next
	Else
	ConsoleWrite(2 & @LF)
	For $ii = 0 To 13
	If Not $ARR[$ii][2] Then
	If $ARR[$ii][3] = $iPlayer Then
	;~ 						GUICtrlSetState($ARR[$ii][0], $GUI_ENABLE)
	GUICtrlSetBkColor($ARR[$ii][0], $DEFAULT)
	Else
	;~ 						GUICtrlSetState($ARR[$ii][0], $GUI_DISABLE)
	GUICtrlSetBkColor($ARR[$ii][0], $GREEN)
	EndIf
	EndIf
	Next
	AdversarioJoga(-$iPlayer)
	EndIf
	Else
	If $FIRST = $iPlayer Then
	ConsoleWrite(3 & @LF)
	For $ii = 0 To 13
	If Not $ARR[$ii][2] Then
	If $ARR[$ii][3] = $iPlayer Then
	;~ 						GUICtrlSetState($ARR[$ii][0], $GUI_DISABLE)
	GUICtrlSetBkColor($ARR[$ii][0], $DEFAULT)
	Else
	;~ 						GUICtrlSetState($ARR[$ii][0], $GUI_ENABLE)
	GUICtrlSetBkColor($ARR[$ii][0], $ORANGE)
	EndIf
	EndIf
	Next
	AdversarioJoga(-$iPlayer)
	Else
	ConsoleWrite(4 & @LF)
	For $ii = 0 To 13
	If Not $ARR[$ii][2] Then
	If $ARR[$ii][3] = $iPlayer Then
	GUICtrlSetBkColor($ARR[$ii][0], 0xFF0000)
	;~ 						GUICtrlSetState($ARR[$ii][0], $GUI_DISABLE)
	Else
	GUICtrlSetBkColor($ARR[$ii][0], 0x00FF00)
	;~ 						GUICtrlSetState($ARR[$ii][0], $GUI_ENABLE)
	EndIf
	EndIf
	Next
	AdversarioJoga($iPlayer)
	EndIf
	EndIf
#ce

;~ #AutoIt3Wrapper_AU3Check_Parameters= -q -d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
;~ #Tidy_Parameters=/sf

; #SCRIPT# ======================================================================================================================
; Name ..........: mancala.au3
; Author ........: Luigi (Luismar Chechelaky)
; Description ...: adaptação do jogo de mancala para AutoIt
; Link ..........: https://github.com/chechelaky/AutoIt/blob/master/mancala/mancala.au3
; webgrafia......: https://pt.wikipedia.org/wiki/Mancala
;                  http://www.colegioglauciacosta.com.br/moodle/file.php/1/Regras_Awele_CLMasse.pdf
;                  http://www.math.ku.dk/famos/.arkiv/22-1/kalaha.pdf
;                  http://fritzdooley.com/mancala/4_computer-aided_game_strategy_reverse_induction.html
; Todo...........: implementar a verificação do vencedor
; ===============================================================================================================================

#include-once
#include <Array.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>

OnAutoItExitRegister("OnExit")

Opt("GUIOnEventMode", 1)
Opt("GUIEventOptions", 1)
Opt("MustDeclareVars", 1)

Global $aGuiSize[2] = [1200, 400]
Global $sGuiTitle = "GuiTitle"
Global $hGui
Global $dummy
Global $hPlayerA, $hPlayerB

$hGui = GUICreate($sGuiTitle, $aGuiSize[0], $aGuiSize[1])
GUISetOnEvent($GUI_EVENT_CLOSE, "Quit")
$dummy = GUICtrlCreateButton("", 0, 0, 0, 0)
Botoes()

$hPlayerA = GUICtrlCreateLabel("A[ 24 ]", 10, 320, 80, 25)
$hPlayerB = GUICtrlCreateLabel("B[ 24 ]", 10, 340, 80, 25)

Global $QuemJogou = 0 ; 0(Escolher), 1(Cima), 2(Baixo)

GUISetState(@SW_SHOW, $hGui)

While Sleep(25)
WEnd

Func Botoes()
	Local $iIntervalo = 20, $half = $iIntervalo / 2
	Local $iLargura = Int(($aGuiSize[0] - $iIntervalo * 9) / 8)

	Global $CASAS[14], $PEDRAS[14] = [4, 4, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4, 0]
	For $ii = 0 To 13
		Switch $ii
			Case 0, 1, 2, 3, 4, 5
				$CASAS[$ii] = GUICtrlCreateButton($PEDRAS[$ii], $iIntervalo + ($iIntervalo + $iLargura) * ($ii + 1), $iIntervalo * 2 + $iLargura, $iLargura, $iLargura, Default, $WS_EX_TOPMOST)
			Case 6
				$CASAS[$ii] = GUICtrlCreateButton($PEDRAS[$ii], $iIntervalo * 8 + $iLargura * 7, $iIntervalo, $iLargura, $iLargura * 2 + $iIntervalo, $SS_SUNKEN)
			Case 13
				$CASAS[$ii] = GUICtrlCreateButton($PEDRAS[$ii], $iIntervalo, $iIntervalo, $iLargura, $iLargura * 2 + $iIntervalo, $SS_SUNKEN)
			Case 7, 8, 9, 10, 11, 12
				$CASAS[$ii] = GUICtrlCreateButton($PEDRAS[$ii], $iIntervalo + ($iIntervalo + $iLargura) * (13 - $ii), $iIntervalo, $iLargura, $iLargura)
		EndSwitch
		GUICtrlSetTip($CASAS[$ii], $CASAS[$ii], "$ii[" & $ii & "]")
		GUICtrlSetOnEvent($CASAS[$ii], "Evento")
		GUICtrlSetFont($CASAS[$ii], 40, 400, 0, "Courier New")
	Next
EndFunc   ;==>Botoes

Func QuemJogou($in)
	Switch $in
		Case $CASAS[0] To $CASAS[0] + 6
			Return 1
		Case $CASAS[0] + 7 To $CASAS[0] + 13
			Return 2
	EndSwitch
EndFunc   ;==>QuemJogou

Func _DePara($in)
	Switch $in
		Case 4 To 9, 11 To 16
			Return $CASAS[13] - $in + $CASAS[0]
		Case Else
			Return 0
	EndSwitch
EndFunc   ;==>_DePara

Func Evento()
	Local $JOGA_MAIS_UMA_VEZ = False

	; identifica quem está jogando
	$QuemJogou = QuemJogou(@GUI_CtrlId)
	; verifica quantas pedrás existem na casa
	; caso não haje nenhuma pedra ou seja uma KALA, interrompe
	Local $QuantasPedras = GUICtrlRead(@GUI_CtrlId)
	If Not Number($QuantasPedras) Or @GUI_CtrlId = 10 Or @GUI_CtrlId = 17 Then Return

	ConsoleWrite("QuantasPedras[ " & $QuantasPedras & " ]" & @LF)
	; zera as pedras da casa
	GUICtrlSetData(@GUI_CtrlId, 0)
	Local $try

	; calcula o loop, baseado na quantidade de sementes
	; e distribui uma semente para cada uma das próximas casas
	For $ii = 1 To $QuantasPedras
		$try = @GUI_CtrlId + $ii
		If $try - $CASAS[0] > 13 Then $try -= 14
		GUICtrlSetData($try, GUICtrlRead($try) + 1)
	Next
	; define a kala do jogador
	Local $kala = $QuemJogou = 2 ? 17 : 10
	; verifica se a última casa onde foi depositada a semente é uma kala
	; se for kala, joga mais uma vez
	If $try = $kala Then
		$JOGA_MAIS_UMA_VEZ = True
		GUICtrlSetState(@GUI_CtrlId, $GUI_DISABLE)
	EndIf

	ConsoleWrite("@[ " & @GUI_CtrlId & " ] $try[ " & $try & " ]  _DePara[ " & _DePara($try) & " ] $QuantasPedras[" & $QuantasPedras & "] $ii[" & $ii & "] $QuemJogou[" & $QuemJogou & "]" & @LF)
	; verifica se a ultima casa possui uma semente, e se na casa do adversário há sementes
	; caso afirmativo, pega as sementes do adversário e movimenta para a kala
	Local $DePara = _DePara($try)
	If Number(GUICtrlRead($try)) = 1 And Number(GUICtrlRead($DePara)) Then
		ConsoleWrite("KALA" & @LF)
		GUICtrlSetData($kala, GUICtrlRead($try) + GUICtrlRead($DePara) + GUICtrlRead($kala))
		GUICtrlSetData($try, 0)
		GUICtrlSetData($DePara, 0)
		GUICtrlSetState(@GUI_CtrlId, $GUI_DISABLE)
		GUICtrlSetState($try, $GUI_DISABLE)
		GUICtrlSetState($DePara, $GUI_DISABLE)

		$JOGA_MAIS_UMA_VEZ = True
	EndIf

	; desabilita as casas sem sentes e do jogador adversário
	; habilita as casas do jogador que possuem sementes
	If $JOGA_MAIS_UMA_VEZ Then

	Else
		Switch $QuemJogou
			Case 1
				For $ii = $CASAS[0] To $CASAS[0] + 5
					GUICtrlSetState($ii, $GUI_DISABLE)
				Next

				For $ii = $CASAS[0] + 7 To $CASAS[0] + 13
					If Number(GUICtrlRead($ii)) Then GUICtrlSetState($ii, $GUI_ENABLE)
				Next
			Case 2
				For $ii = $CASAS[0] To $CASAS[0] + 6
					If Number(GUICtrlRead($ii)) Then GUICtrlSetState($ii, $GUI_ENABLE)
				Next

				For $ii = $CASAS[0] + 7 To $CASAS[0] + 12
					GUICtrlSetState($ii, $GUI_DISABLE)
				Next
		EndSwitch
	EndIf
	GUICtrlSetState($dummy, $GUI_FOCUS)
	HouveGanhador()
EndFunc   ;==>Evento

Func HouveGanhador()
	Local $iPlayerA = 0
	Local $iPlayerB = 0
	For $ii = 4 To 10
		$iPlayerA += GUICtrlRead($ii)
		$iPlayerB += GUICtrlRead($ii + 7)
	Next
	GUICtrlSetData($hPlayerA, "A[ " & $iPlayerA & " ]")
	GUICtrlSetData($hPlayerB, "B[ " & $iPlayerB & " ]")
EndFunc   ;==>HouveGanhador

Func OnExit()
	GUISetState($hGui, @SW_HIDE)
	GUIDelete($hGui)
EndFunc   ;==>OnExit

Func Quit()
	Exit
EndFunc   ;==>Quit


removed debug msg

removed debug msg

#include <config.au3>
#include <utils.au3>

Func botStart()
   bluestacksShow()
   btnToggle('start bot', $CLASBOT_WINDOW_TOGGLE_START, 'start bot', 'stop')
EndFunc

Func botStop()
   bluestacksHide()
   btnToggle('stop', $CLASBOT_WINDOW_TOGGLE_START, 'start bot', 'stop')
EndFunc

Func bluestacksShow()
   btnToggle('show bluestacks', $CLASBOT_WINDOW_TOGGLE_HIDE, 'show bluestacks', 'hide bluestacks')
EndFunc

Func bluestacksHide()
   btnToggle('hide bluestacks', $CLASBOT_WINDOW_TOGGLE_HIDE, 'show bluestacks', 'hide bluestacks')
EndFunc

Func btnToggle($action = '', $toggleBtn = '', $textOptionA = '', $textOptionB = '')
   If Not isClashBotRunning() AND Not isLoggedIn() Then
	  msgNotify('err', 'clash bot not running.')
	  ; Not running and not logged in.. Strage state.
	  Return False
   EndIf

   WinActivate($CLASBOT_WINDOW) ; brint to front each toggle. might prevent some odd bugs.

   Local $btnToggleText = ControlGetText($CLASBOT_WINDOW, '', $toggleBtn)

   If ('' == $action) OR ($textOptionA == StringLower($btnToggleText) AND $textOptionA == $action) OR ($textOptionB == StringLower($btnToggleText) AND $textOptionB == $action) Then
	  click($CLASBOT_WINDOW, $toggleBtn)
   Else
	  ; invalid state or already in the requested state.
   EndIf

EndFunc

Func closeClashBotApp()
   Local $hWnd = WinGetHandle($CLASBOT_WINDOW)

   If isClashBotRunning() Then
      WinWait($hWnd, '', 5);
      WinClose($hWnd);
   EndIf
EndFunc

Func loadClashBotApp()
   Local $hWnd = WinGetHandle($CLASBOT_WINDOW)

   If Not isClashBotRunning() Then
	  runBot()
   ElseIf Not isLoggedIn() Then
	  login()
   Else
	  ; all good.. continue. not extra steps needed.
   EndIf

   WinActivate($CLASBOT_WINDOW) ; bring to front.
EndFunc

Func login()
   WinWait($CLASBOT_WINDOW, '', 10)
   Sleep(1000)

   If Not isLoggedIn() Then
	  click($CLASBOT_WINDOW, $CLASBOT_WINDOW_BTN_LOGIN)
	  closeConfirmationBox()
   EndIf
EndFunc

Func closeConfirmationBox()
   WinWait($CLASBOT_CONFIRM_WINDOW, '', 5);
   WinClose($CLASBOT_CONFIRM_WINDOW);
EndFunc

Func runBot()
   Run($CLASHBOT_PATH & $CLASHBOT_EXEC, $CLASHBOT_PATH)

   login()
EndFunc

Func isLoggedIn()
   WinWait($CLASBOT_WINDOW, '', 10)
   Local $loginBtn = ControlGetHandle($CLASBOT_WINDOW, '', $CLASBOT_WINDOW_BTN_LOGIN);

   If @error AND isClashBotRunning() Then
	  Return True
   Else
	  Return False
   EndIf
EndFunc

Func isClashBotRunning()
   Local $hWnd = WinGetHandle($CLASBOT_WINDOW)

   If @error Then
	  Return False
   Else
	  Return True
   EndIf
EndFunc

Func isStarted()
   If Not isClashBotRunning() AND Not isLoggedIn() Then
	  ; msgNotify('err', 'clash bot not running.')
	  ; Not running and not logged in.. Strage state.
	  Return False
   EndIf

   Local $btnToggleText = ControlGetText($CLASBOT_WINDOW, '', $CLASBOT_WINDOW_TOGGLE_START)

   If 'Stop' == $btnToggleText Then
      Return True
   Else
      Return False
   EndIf
EndFunc

#include <config.au3>
#include <utils.au3>

Func botStart()
   bluestacksShow()
   btnToggle('start bot', $CLASBOT_WINDOW_TOGGLE_START, 'start bot', 'stop')
EndFunc

Func botStop()
   bluestacksHide()
   btnToggle('stop', $CLASBOT_WINDOW_TOGGLE_START, 'start bot', 'stop')
EndFunc

Func bluestacksShow()
   btnToggle('show bluestacks', $CLASBOT_WINDOW_TOGGLE_HIDE, 'show bluestacks', 'hide bluestacks')
EndFunc

Func bluestacksHide()
   btnToggle('hide bluestacks', $CLASBOT_WINDOW_TOGGLE_HIDE, 'show bluestacks', 'hide bluestacks')
EndFunc

Func btnToggle($action = '', $toggleBtn = '', $textOptionA = '', $textOptionB = '')
   If Not isClashBotRunning() AND Not isLoggedIn() Then
	  msgNotify('err', 'clash bot not running.')
	  ; Not running and not logged in.. Strage state.
	  Return False
   EndIf

   WinActivate($CLASBOT_WINDOW) ; brint to front each toggle. might prevent some odd bugs.

   Local $btnToggleText = ControlGetText($CLASBOT_WINDOW, '', $toggleBtn)

   If ('' == $action) OR ($textOptionA == StringLower($btnToggleText) AND $textOptionA == $action) OR ($textOptionB == StringLower($btnToggleText) AND $textOptionB == $action) Then
	  click($CLASBOT_WINDOW, $toggleBtn)
   Else
	  ; invalid state or already in the requested state.
   EndIf

EndFunc

Func closeClashBotApp()
   Local $hWnd = WinGetHandle($CLASBOT_WINDOW)

   If isClashBotRunning() Then
      WinWait($hWnd, '', 5);
      WinClose($hWnd);
   EndIf
EndFunc

Func loadClashBotApp()
   Local $hWnd = WinGetHandle($CLASBOT_WINDOW)

   If Not isClashBotRunning() Then
	  runBot()
   ElseIf Not isLoggedIn() Then
	  login()
   Else
	  ; all good.. continue. not extra steps needed.
   EndIf

   WinActivate($CLASBOT_WINDOW) ; bring to front.
EndFunc

Func login()
   WinWait($CLASBOT_WINDOW, '', 10)
   Sleep(1000)

   If Not isLoggedIn() Then
	  click($CLASBOT_WINDOW, $CLASBOT_WINDOW_BTN_LOGIN)
	  closeConfirmationBox()
   EndIf
EndFunc

Func closeConfirmationBox()
   WinWait($CLASBOT_CONFIRM_WINDOW, '', 5);
   WinClose($CLASBOT_CONFIRM_WINDOW);
EndFunc

Func runBot()
   Run($CLASHBOT_PATH & $CLASHBOT_EXEC, $CLASHBOT_PATH)

   login()
EndFunc

Func isLoggedIn()
   WinWait($CLASBOT_WINDOW, '', 10)
   Local $loginBtn = ControlGetHandle($CLASBOT_WINDOW, '', $CLASBOT_WINDOW_BTN_LOGIN);

   If @error AND isClashBotRunning() Then
	  Return True
   Else
	  Return False
   EndIf
EndFunc

Func isClashBotRunning()
   Local $hWnd = WinGetHandle($CLASBOT_WINDOW)

   If @error Then
	  Return False
   Else
	  Return True
   EndIf
EndFunc

Func isStarted()
   If Not isClashBotRunning() AND Not isLoggedIn() Then
	  msgNotify('err', 'clash bot not running.')
	  ; Not running and not logged in.. Strage state.
	  Return False
   EndIf

   Local $btnToggleText = ControlGetText($CLASBOT_WINDOW, '', $CLASBOT_WINDOW_TOGGLE_START)

   If 'Stop' == $btnToggleText Then
      Return True
   Else
      Return False
   EndIf
EndFunc