﻿B4A=true
Group=ATLAS CM\SERVICES
ModulesStructureVersion=1
Type=Service
Version=7.8
@EndOfDesignText@
#Region  Service Attributes 
	#StartAtBoot: False
	
#End Region


Sub Process_Globals
	'These global variables will be declared once when the application starts.
	'These variables can be accessed from all modules.
	
	Dim wsh					As WebSocketHandler
	Dim link				As String
	Dim tmrKillMe 			As Timer
	Dim svrReady			As Boolean
	Dim loginReady			As Boolean
	Dim serviceRunning		As Boolean
	Dim Ihavefailed			As Boolean
	
End Sub

Sub Service_Create
	
	mod_functions.writelog("svc_wsh_login::Service_Create()")
	tmrKillMe.Initialize("kill","10000")
	link  = "wss://" & Starter.appset.ws.host & ":" & Starter.appset.ws.port & "/login"
	wsh.Initialize(Me, "wsh")
	
	' // we must rest these flags, regarless of the result
	Starter.appset.LoginReconnect = 0
	' // 2026.10.15
	mod_functions.CheckHeapMemory("svc_wsh_login::Service_Create")
	
End Sub

Sub Service_Start (StartingIntent As Intent)

	' // 2020.12.14 - Prevent this service from exiting is called while we already have a connection
	If serviceRunning Then
		mod_functions.writelog("svc_wsh_login::Service_Start(), service already running")
		Return
	Else
		serviceRunning = True
	End If
		
	mod_functions.writelog($"svc_wsh_login::Service_Start::Connecting to ${link}"$)
	
	svrReady = False
	loginReady = False
	
	If svc_service.mlWifi.isOnline Then
		Try
			tmrKillMe.Enabled = True
			wsh.Connect(link)
		Catch
			mod_functions.writelog("svc_wsh_login::Service_Start() error - " & LastException.Message )
			tmrKillMe.Enabled = False
			StopService(Me)
		End Try
	Else
		mod_functions.writelog("svc_wsh_login::Service_Start() NO INTERNET CONNECTION AVAILABLE")
		tmrKillMe.Enabled = False
		StopService(Me)
	End If
		
End Sub

Sub Service_Destroy
	
	mod_functions.writelog("svc_wsh_login::Service_Destroy()")
	
	tmrKillMe.Enabled = False
	serviceRunning = False
	' // update MAIN
	If Starter.appset.currentActivity = "main" Then
		If Starter.appset.app_active Then
			CallSubDelayed(Main,"show_user_state")
		End If
	End If
	' // update MESSAGING
	If Starter.appset.currentActivity = "messaging" Then
		If Starter.appset.app_active Then
			CallSubDelayed(Messaging,"set_toolbar_color")
		End If
	End If
	' // update MESSAGING
	If Starter.appset.currentActivity = "messagingitems" Then
		If Starter.appset.app_active Then
			CallSubDelayed(MessagingItems,"set_toolbar_color")
		End If
	End If
	' // update PAGES
	If Starter.appset.currentActivity = "pages" Then
		If Starter.appset.app_active Then
			CallSubDelayed(CMPages,"set_toolbar_color")
		End If
	End If
	
	' //we are not online
	If Starter.appset.profile.state <> mod_core_consts.STATE_ONLINE Then
		' // flag to try again if we are not logging off
		If Starter.appset.loginType = mod_core_consts.REQUEST_LOGON Then
			Starter.appset.LoginReconnect = DateTime.Now + (DateTime.TicksPerSecond * mod_core_consts.LOGINRECONNECT_RETRY)
			mod_functions.writelog("svc_wsh_login::Service_Destroy::Retry @ " & DateTime.Time(Starter.appset.LoginReconnect))
		End If
	End If
	
	' // we need reset our connection to the server
	If Ihavefailed Then
		Ihavefailed = False
		CallSubDelayed(svc_service,"ping_close")
	End If
	
	' // 2026.10.15
	Try
		wsh = Null
	Catch
		mod_functions.writelog($"svc_wsh_login::Service_Destroy:: -error- ${LastException.Message}"$)
	End Try
	mod_functions.CheckHeapMemory("svc_wsh_login::Service_Destroy")
	
End Sub

Sub Kill_Tick
	
	mod_functions.writelog("svc_wsh_login::Kill_Tick:: connection to server timeout")
	tmrKillMe.Enabled = False	
	StopService(Me)

End Sub

#region SENDERS
Sub sendlogin
	
	Dim data As Map 
	data.Initialize

	mod_functions.writelog("svc_wsh_login::sendlogin, Device ID = " & Starter.appset.imei)
	
	data.Put("imei", Starter.appset.imei)
	' // 2021.06.21 - Tell Server SOS is installed
	data.Put("sos_installed", Starter.appset.sos_installed)

	If Not(wsh.SendEventToServer("Login_Credentials", data)) Then
		Ihavefailed = True
		StopService(Me)
	End If
	
End Sub

Sub sendlogoff
	
	Dim data As Map
	
	data.Initialize
	data.Put("session_id", Starter.appset.profile.session_id)
	If Not(wsh.SendEventToServer("Logoff_Credentials", data)) Then
		Ihavefailed = True
		StopService(Me)
	End If
	
End Sub

Sub sendlogoffUntil
	
	' // logoff until Cancel
	Dim data As Map
	data.Initialize
	data.Put("public_id", Starter.appset.profile.public_id)
	data.Put("logoff_until", Starter.appset.LogoffUntil)
	If Not(wsh.SendEventToServer("logoff_until", data)) Then
		Ihavefailed = True
		StopService(Me)
	End If
	
End Sub

#End Region

#region WSH


Sub wsh_LogoffUntilResponse(Params As List)
	
	mod_functions.writelog("svc_wsh_login::wsh_LogoffUntilResponse:: " & Params.get(0))
	mod_settings.put_LogoffUntil
	Starter.appset.profile.state = mod_core_consts.STATE_OFFLINE
	mod_functions.writelog($"svc_wsh_login::wsh_LogoffUntilResponse:: We are offline"$)
	wsh.close
	
	If Not(IsPaused(svc_wsh_messaging)) Then
		StopService(svc_wsh_messaging)
	End If
	
	' // 2023.01.17 - send a status report
	mod_functions.send_status_event
	
		
End Sub

Sub wsh_Connected
	
	'tmrKillMe.Enabled = False
	
End Sub

Sub wsh_Closed (Reason As String)
	
	mod_functions.writelog("svc_wsh_login::wsh_Closed, Reason=" & Reason)
	' // we did not get a valid connection
	If Not(svrReady) Or Not(loginReady) Then
		Starter.appset.profile.state = mod_core_consts.STATE_OFFLINE
		svc_service.setNotification = 1
		Starter.appset.LoginReconnectCount = Starter.appset.LoginReconnectCount + 1
		mod_functions.writelog($"svc_wsh_login::wsh_Closed:: We are offline :("$)		
	Else
		' // 2024.07.01 - reset counter
		Starter.appset.LoginReconnectCount = 0
		mod_functions.writelog($"svc_wsh_login::wsh_Closed:: We are online :)"$)
	End If
	
	StopService(Me)
	
End Sub

Sub wsh_ServerLoginResult(Params As List)
	
	Dim doPermissions 	As Boolean
	Dim rp				As RuntimePermissions
	
	loginReady = True
	
	If Params.Get(0) = "FAILED" Then
		' // reset the profile
		Starter.appset.profile.session_id = ""
		Try
			svc_service.setNotification = 1
		Catch
			mod_functions.writelog("svc_wsh_login::wsh_ServerLoginResult(#1) error - " & LastException.Message )
		End Try
		
		Starter.appset.profile.state = mod_core_consts.STATE_OFFLINE
		Try
			Starter.appset.profile.loginfailed_code	= Params.Get(1)
		Catch
			mod_functions.writelog("svc_wsh_login::wsh_ServerLoginResult(#1) error - " & LastException.Message )
		End Try
		
		If Starter.appset.profile.loginfailed_code > 0 Then
			ToastMessageShow(Starter.loc.Localize("login_error_" & Starter.appset.profile.loginfailed_code),True)
			If Starter.appset.app_active Then
				CallSubDelayed3(Main,"show_system_message","login_error_" & Starter.appset.profile.loginfailed_code,True)
				' // call the reg screen
				If Starter.appset.profile.loginfailed_code = 1 Then
					CallSubDelayed(Main,"load_dev_info")
				End If
			Else				
				' // reset
				Starter.appset.profile.loginfailed_code = 0
				' // if screen on
				If Starter.appset.screen_on Then
					Starter.appset.LoginReconnect = DateTime.Now + (DateTime.TicksPerSecond * mod_core_consts.LOGINRECONNECT_RETRY)
				Else
					Starter.appset.LoginReconnect = DateTime.Now + (DateTime.TicksPerSecond * Starter.appset.profile.ping_freq)
				End If
				mod_functions.writelog($"svc_wsh_login::aStream_NewData::Starter.appset.LoginReconnect=$Time{Starter.appset.LoginReconnect}"$)
			End If
		End If
		
	Else
		
		Try 			
			
'			Log(Params.Size)
'			Dim zxc As Int
'			For zxc = 0 To Params.Size-1
'				Log($"${zxc}=${Params.Get(zxc)}"$)
'			Next
			
			' // prime the profile		
			Starter.appset.profile.session_id 	= Params.Get(0)
			Starter.appset.profile.name 		= Params.Get(1)
			Starter.appset.profile.public_id 	= Params.Get(2)
			Starter.appset.profile.ping_freq 	= Params.Get(3)
			Starter.appset.profile.state		= mod_core_consts.STATE_ONLINE
			Starter.appset.profile.loginfailed_code = 0
			' // Manage Alert Settings
			Starter.appset.actions_titles.manage_alert	= Params.Get(4)
			Starter.appset.actions_titles.manage_alert_additional = Params.Get(5)
			Starter.appset.actions_titles.manage_suppress_confirmation = Params.Get(6)
			' // False Alert Settings
			Starter.appset.actions_titles.false_alert = Params.Get(7)
			Starter.appset.actions_titles.false_alert_additional = Params.Get(8)
			Starter.appset.actions_titles.false_suppress_confirmation = Params.Get(9)
			' // Close Alert Settings
			Starter.appset.actions_titles.close_alert	= Params.Get(10)
			Starter.appset.actions_titles.close_alert_additional = Params.Get(11)
			Starter.appset.actions_titles.close_suppress_confirmation = Params.Get(12)
			' // Response Buttons Titles
			Starter.appset.descriptors.open		= Params.Get(13)
			Starter.appset.descriptors.managed	= Params.Get(14)
			Starter.appset.descriptors.closed	= Params.Get(15)
			' // Mapping Content Management
			Starter.appset.content.MapAutoLoadEnabled			= Params.Get(16)
			Starter.appset.content.MapAutoLoadFilters			= Params.Get(17)
			Starter.appset.content.MapFiltersStopAfterFirstHit	= Params.Get(18)		
			' // smsg address
			Starter.appset.sms_gateway_address	= Params.Get(19)
			' // pincode
			Starter.appset.passcode	= Params.Get(20)
			' // ping port
			Starter.appset.pingport	= Params.Get(21)
			Starter.appset.idledisconnect = Params.Get(22)
		Catch
			mod_functions.writelog("svc_wsh_login::wsh_ServerLoginResult(#2) error - " & LastException.Message )
		End Try
		
		Try
			If Params.Size > 23 Then
				' // 2023.01.16 - mobile ping freq
				Starter.appset.profile.ping_freq_mobile = Params.Get(23)
				' // 2023.01.16 - status messages
				Starter.appset.sm.dns = Params.Get(24)
				Starter.appset.sm.ssl_host = Params.Get(25)
				Starter.appset.sm.ssl_port = Params.Get(26)
				Starter.appset.sm.http_host = Params.Get(27)
				Starter.appset.sm.http_port = Params.Get(28)
				Starter.appset.sm.https_port = Params.Get(29)
				Starter.appset.sm.sm_message_freq = Params.Get(30)
				Starter.appset.sm.sm_flp_freq = Params.Get(31)
			End If
		Catch
			mod_functions.writelog("svc_wsh_login::wsh_ServerLoginResult(#3) error - " & LastException.Message )
		End Try
		
		' // 2023.09.04 - loc/dep
		' // element sys_sac_res(32) is not used
		Try 
			If Params.Size > 31 Then
				Starter.appset.profile.location = Params.Get(33)
				Starter.appset.profile.department = Params.Get(34)			
			End If
		Catch
			mod_functions.writelog("svc_wsh_login::wsh_ServerLoginResult(#4) error - " & LastException.Message )
		End Try
		
		' // 2024.07.02
		#if not(playstore)
			If Starter.appset.sm.sm_flp_freq > 0  Then
				mod_functions.writelog($"svc_wsh_login::wsh_ServerLoginResult::PERMISSION_ACCESS_COARSE_LOCATION::${rp.Check(rp.PERMISSION_ACCESS_COARSE_LOCATION)}"$)
				If Not(rp.Check(rp.PERMISSION_ACCESS_COARSE_LOCATION)) Then
					doPermissions = True
				End If
				mod_functions.writelog($"svc_wsh_login::wsh_ServerLoginResult::PERMISSION_ACCESS_FINE_LOCATION::${rp.Check(rp.PERMISSION_ACCESS_FINE_LOCATION)}"$)
				If Not(rp.Check(rp.PERMISSION_ACCESS_FINE_LOCATION)) Then
					doPermissions = True
				End If
			End If
		#end if
		
		' // write the profile
		mod_settings.write_profile
		' // write the pin code
		mod_settings.put_passcode
		' // write the ping port
		mod_settings.put_pingport
		' // write the idle disconnect
		mod_settings.put_idledisconnect
		
		Try
			' // flag notification icon to update
			svc_service.setNotification = 1
		Catch
			mod_functions.writelog("svc_wsh_login::wsh_ServerLoginResult(#3) error - " & LastException.Message )
		End Try
	
		If Starter.appset.currentActivity = "main" Then
			If Starter.appset.app_active Then
				CallSubDelayed(Main,"load_alert_dashboard")
			End If
		End If
		
		' // location permissions
		If doPermissions Then
			mod_functions.writelog($"svc_wsh_login::wsh_ServerLoginResult::starter.appset.sm.sm_flp_freq=${Starter.appset.sm.sm_flp_freq}"$)
			If Not(Starter.appset.app_active) Then
				StartActivity(Main)
			Else
				CallSubDelayed(Main,"check_permission_all")
			End If
		End If
		
		' // 2026.10.14
		Starter.appset.profile.state = mod_core_consts.STATE_ONLINE
		Starter.appset.LoginReconnect = 0
			
		mod_functions.writelog($"svc_wsh_login::wsh_ServerLoginResult::session id=${Starter.appset.profile.session_id},Starter.appset.LoginReconnect=${Starter.appset.LoginReconnect},Starter.appset.profile.state=${Starter.appset.profile.state}"$)
	End If
	Params.Clear
	' // close the connection
	wsh.Close	
	
	mod_functions.requestData("com.islesystems.launcher","speechvolume")
	
End Sub

Sub wsh_ServerLogoff(Params As List)
	
	
	If Starter.appset.LogOffAndExit <>  0 Then
		Starter.appset.LogOffAndExit =  mod_core_consts.REQUEST_LOGOFF_COMPLETED		
	End If
	
	' // reset profile	
	Starter.appset.profile.state = mod_core_consts.STATE_OFFLINE
	mod_functions.writelog($"svc_wsh_login::wsh_ServerLogoff:: We are offline"$)
	Try
		svc_service.setNotification = 1
	Catch
		mod_functions.writelog("svc_wsh_login::wsh_ServerLogoff() error - " & LastException.Message )
	End Try
	' // close the connection
	wsh.Close
	
End Sub

Sub wsh_ServerReady(Params As List)
	
	Dim s As String
		
	' // example of a server push message
	s = Params.Get(0)
	
	If s = "READY" Then
		svrReady = True
		mod_functions.writelog($"svc_wsh_login::wsh_ServerReady() Server Response ${s}, ${Starter.appset.loginType} "$ )
		Try
			Starter.appset.profile.cm_server_id = Params.Get(1)
			mod_settings.put_cm_svr_id
			mod_functions.writelog($"svc_wsh_login::wsh_ServerReady() CM Server ID ${Starter.appset.profile.cm_server_id}"$ )
		Catch
			mod_functions.writelog($"svc_wsh_login::Response ${s} received. The cm_server_id was not sent. You may not be connected to the correct port - ${link} "$ )
		End Try
		' // if we are not online - 
		If Starter.appset.loginType = mod_core_consts.REQUEST_LOGON Then
			CallSubDelayed(Me,"sendlogin")
		End If
		If Starter.appset.loginType = mod_core_consts.REQUEST_LOGOFF Then
			CallSubDelayed(Me,"sendlogoff")
		End If
		If Starter.appset.loginType = mod_core_consts.REQUEST_LOGOFF_UNTIL Then
			' // logoff request
			CallSubDelayed(Me,"sendlogoffUntil")
		End If
	Else
		wsh.Close
	End If
	
End Sub

#End Region
