﻿B4A=true
Group=ATLAS CM\CLASS
ModulesStructureVersion=1
Type=Class
Version=7.8
@EndOfDesignText@
'Class module
#Event: Connected
#Event: Closed (Reason As String)
Sub Class_Globals
	
	Public ws As WebSocket, connected As Boolean
	
	Private CallBack 	As Object
	Private EventName 	As String
	Private link 		As String
	Private ctm 		As CustomTrustManager
	
End Sub

Public Sub Initialize (vCallback As Object, vEventName As String)
	
	CallBack = vCallback
	EventName = vEventName
	
	init_socket

End Sub

Public Sub Connect(Url As String)
	
	link = Url
	
	Try
		' // attempt connection
		ws.Connect(link)
		mod_functions.writelog($"WebSocketHandler::Connect to ${link}"$)
	Catch
		mod_functions.writelog("WebSocketHandler:Connect() error - " & LastException.Message)
		connected = False
		Close
	End Try
	
	
End Sub

Public Sub Close
	
	connected = False
	mod_functions.writelog($"WebSocketHandler::Closed ${link}"$)
	ws.Close
	CallSub2(CallBack, EventName & "_Closed", "Closed")
	
End Sub

public Sub init_socket
	
	ctm.InitializeAcceptAll
	ws.Initialize("ws")
	ws.SetCustomSSLTrustManager(ctm)
	
	' // set the connection timeout to 5 seconds
	Dim options As JavaObject = ws
	options.GetFieldJO("options").RunMethod("setSocketConnectTimeout", Array(5000))
	
End Sub

'Raises an event on the server. The Event parameter must include an underscore
Public Sub SendEventToServer(Event As String, Data As Map) As Boolean
	
	Dim res As Boolean = True
	
	Try
		If connected Then
			Dim m As Map
			m.Initialize
			m.Put("type", "event")
			m.Put("event", Event)
			m.Put("params", Data)
			Dim jg As JSONGenerator
			jg.Initialize(m)
			ws.SendText(jg.ToString)
		Else
			Log("SendEventToServer: Not Connected")
		End If
	Catch
		Log($"SendEventToServer: ${LastException}"$)
		res = False
	End Try
	
	Return res
	
End Sub


Private Sub ws_TextMessage(msg As String)

	Try
		Dim jp As JSONParser
		jp.Initialize(msg)
		Dim m As Map = jp.NextObject
		Dim etype As String = m.get("etype")
		Dim params As List = m.get("value")
		Dim event As String = m.get("prop")
		If etype = "runFunction" Then
			If SubExists(CallBack,EventName & "_" & event) Then
				CallSub2(CallBack, EventName & "_" & event, params)
			End If
		End If
	Catch
		Log("TextMessage Error: " & LastException)
	End Try
End Sub


Private Sub ws_Connected
	connected = True
	CallSub(CallBack,  EventName & "_Connected")
End Sub

Private Sub ws_Closed (Reason As String)
	connected = False
	CallSub2(CallBack, EventName & "_Closed", Reason)
End Sub