Compile subroutine MONA_SERVICES(@Service, @Params)
/***********************************************************************************************************************
This subroutine is used to send messages to MonA directly from
within OpenInsight. It utilizes a C# DotNet DLL MonAOIApi.dll
which contains two classes, one for sending status updates, and
one for sending metrics. Also requires the Infineon.Monitoring.Mona.dll which contains the needed dotnet libraries.

Parameters:
Instruction: Used to determine which subroutine to execute.
Parm1:
    -For Status updates represents the name of the monitor
    -For Metrics updates represents the name of the monitor
Parm2:
    -For Status updates represents the name of the status
    -For Metric updates represents the name of the metric
Parm3:
    -For status updates this represents the state of the object you are sending(Ok, Warning, Critical)
    -For Metric updates this represents the numeric data that you wish to send.
    
***********************************************************************************************************************/
#pragma precomp SRP_PreCompiler

$Insert APP_INSERTS
$Insert SERVICE_SETUP
$Insert MONA_QUEUE_EQUATES

Equ MAX_REQUESTS$ to 2000
Equ COMMA$        to ','

Declare Subroutine Errmsg, Error_Services, Delay, Mona_Services, Service_Services, Database_Services, Logging_Services
Declare subroutine SRP_Json, obj_Notes
Declare function   Get_Status, SRP_Datetime, Environment_Services, Httpclient_Services, Datetime, RTI_CreateGuid
Declare function   Database_Services, Logging_Services, SRP_Json, Mona_Services

GoToService else
	Error_Services('Add', Service : ' is not a valid service request within the ' : ServiceModule : ' services module.')
end

return Response else ''

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Service Parameter Options
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Options MONITORS     = 'SQL_BACKLOG', 'SQL_BACKLOG_WO_MAT', 'SQL_BACKLOG_WO_LOG'
Options STATES       = 'OK', 'WARNING', 'CRITICAL'
Options REQUEST_TYPE = 'status', 'average', 'count', 'status/bulk', 'average/bulk', 'count/bulk'

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Services
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Service PostStatus(MonitorName, StatusName, CurrentState=STATES)
	
	MonaQId                            = RTI_CreateGuid()
	MonaQRec                           = ''
	MonaQRec<MONA_QUEUE.REQUEST_DTM$>  = Datetime()
	MonaQRec<MONA_QUEUE.MONITOR_NAME$> = MonitorName
	MonaQRec<MONA_QUEUE.STATUS_NAME$>  = StatusName
	MonaQRec<MONA_QUEUE.STATUS_STATE$> = CurrentState
	Database_Services('WriteDataRow', 'MONA_QUEUE', MonaQId, MonaQRec)
	
end service


Service PostAverageMetric(MonitorName, MetricName, Number)
	
	MonaQId                             = RTI_CreateGuid()
	MonaQRec                            = ''
	MonaQRec<MONA_QUEUE.REQUEST_DTM$>   = Datetime()
	MonaQRec<MONA_QUEUE.MONITOR_NAME$>  = MonitorName
	MonaQRec<MONA_QUEUE.METRIC_NAME$>   = MetricName
	MonaQRec<MONA_QUEUE.METRIC_NUMBER$> = Number
	MonaQRec<MONA_QUEUE.METRIC_TYPE$>   = 'AVERAGE'
	Database_Services('WriteDataRow', 'MONA_QUEUE', MonaQId, MonaQRec)	
	
end service


Service PostCountMetric(MonitorName, MetricName, Number)
	
	MonaQId                             = RTI_CreateGuid()
	MonaQRec                            = ''
	MonaQRec<MONA_QUEUE.REQUEST_DTM$>   = Datetime()
	MonaQRec<MONA_QUEUE.MONITOR_NAME$>  = MonitorName
	MonaQRec<MONA_QUEUE.METRIC_NAME$>   = MetricName
	MonaQRec<MONA_QUEUE.METRIC_NUMBER$> = Number
	MonaQRec<MONA_QUEUE.METRIC_TYPE$>   = 'COUNT'
	Database_Services('WriteDataRow', 'MONA_QUEUE', MonaQId, MonaQRec)		
	
end service


Service QueueLatencyAndCountMetrics(MonaResource, MetricName, StartTick, EndTick)
	
	Diff = EndTick - StartTick
    Mona_Services('PostAverageMetric', MonaResource, MetricName:'_LATENCY', Diff)
    Mona_Services('PostCountMetric', MonaResource, MetricName:'_COUNT', 1)
    
end service


Service ProcessMonaQueue(NumRequests)
	
	hSysLists = Database_Services('GetTableHandle', 'SYSLISTS')
	Lock hSysLists, ServiceKeyID then
		LogPath         = Environment_Services('GetApplicationRootPath') : '\LogFiles\MonA'
		LogDate         = Oconv(Date(), 'D4/')
		LogFileName     = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' MonA Queue Log.csv'
		Headers         = 'Logging DTM':@FM:'Log Data'
		objMonaQueueLog = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, COMMA$, Headers, '', False$, False$)
	
		LogData    = ''
		LogData<1> = OConv(Datetime(), 'DT/^S')
		LogData<2> = 'Begin ProcessMonaQueue'
		Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)
	
		ErrorMsg = ''
		If NumRequests NE '' then
			If Num(NumRequests) then
				NumRequests = Abs(Int(NumRequests))
				If NumRequests GT MAX_REQUESTS$ then
					LogData<1>  = OConv(Datetime(), 'DT/^S')
					LogData<2>  = 'Requested NumRequests ':NumRequests:' is above predefined limit. Overriding NumRequests and setting to ':MAX_REQUESTS$:'.'
					NumRequests = MAX_REQUESTS$
					Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)					
				end
				LogData<1> = OConv(Datetime(), 'DT/^S')
				LogData<2> = 'Attempting to process up to ':NumRequests:' MONA_QUEUE requests.'
				Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)				
				
				Open 'MONA_QUEUE' to hMonaQueue then
					objMonaStatusJsonArray       = ''
					MonaStatusJson               = ''
					objMonaMetricAvgJsonArray    = ''
					MonaMetricAvgJson            = ''
					objMonaMetricCountJsonArray  = ''
					MonaMetricCountJson          = ''
					If SRP_Json(objMonaStatusJsonArray, 'New', 'Array') then 
						If SRP_Json(objMonaMetricAvgJsonArray, 'New', 'Array') then 
							If SRP_Json(objMonaMetricCountJsonArray, 'New', 'Array') then
								DefaultMonitorName = Environment_Services("GetMonaResource")
								EOF                = False$
								RequestCount       = 0
								InvalidRequests    = ''
								StatusRequests     = ''
								AverageRequests    = ''
								CountRequests      = ''
								GoSub ClearCursors
								Select hMonaQueue
								Loop
									Readnext MonaQueueId else EOF = True$
								Until (EOF or (RequestCount GE NumRequests) or (ErrorMsg NE '') )
									RequestCount += 1
									Read MonaQueueRec from hMonaQueue, MonaQueueId then
										Begin Case
											Case ( (MonaQueueRec<MONA_QUEUE.STATUS_NAME$> NE '') and (MonaQueueRec<MONA_QUEUE.STATUS_STATE$> NE '') )
												// Add status object
												objStatus  = ''
												StatusJson = Mona_Services('ConvertRecordToJson', MonaQueueId)
												If Error_Services('NoError') then
													If (SRP_Json(objStatus, 'Parse', StatusJson) EQ '') then
														SRP_Json(objMonaStatusJsonArray, 'Add', objStatus)
														SRP_Json(objStatus, 'Release')
														StatusRequests<-1> = MonaQueueId
														LogData<1>         = OConv(Datetime(), 'DT/^S')
														LogData<2>         = 'Successfully added MONA_QUEUE ':MonaQueueId:' to objMonaStatusJsonArray.'
														Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)																		
													end else
														ErrorMsg = 'Error in ':Service:' service. Error parsing StatusJson json.'
													end
												end else
													ErrorMsg = 'Error in ':Service:' service. Error message: ':Error_Services('GetMessage')
												end
											Case ( (MonaQueueRec<MONA_QUEUE.METRIC_NAME$> NE '') and (MonaQueueRec<MONA_QUEUE.METRIC_NUMBER$> NE '') and (MonaQueueRec<MONA_QUEUE.METRIC_TYPE$> EQ 'AVERAGE') )
												// Add average metric object
												objAverage  = ''
												AverageJson = Mona_Services('ConvertRecordToJson', MonaQueueId)
												If Error_Services('NoError') then
													If (SRP_Json(objAverage, 'Parse', AverageJson) EQ '') then
														SRP_Json(objMonaMetricAvgJsonArray, 'Add', objAverage)
														SRP_Json(objAverage, 'Release')
														AverageRequests<-1> = MonaQueueId
														LogData<1>         = OConv(Datetime(), 'DT/^S')
														LogData<2>         = 'Successfully added MONA_QUEUE ':MonaQueueId:' to objMonaMetricAvgJsonArray.'
														Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)																		
													end else
														ErrorMsg = 'Error in ':Service:' service. Error parsing AverageJson json.'
													end
												end else
													ErrorMsg = 'Error in ':Service:' service. Error message: ':Error_Services('GetMessage')
												end
											Case ( (MonaQueueRec<MONA_QUEUE.METRIC_NAME$> NE '') and (MonaQueueRec<MONA_QUEUE.METRIC_NUMBER$> NE '') and (MonaQueueRec<MONA_QUEUE.METRIC_TYPE$> EQ 'COUNT') )
												// Add count metric object
												objCount          = ''
												CountJson = Mona_Services('ConvertRecordToJson', MonaQueueId)
												If Error_Services('NoError') then
													If (SRP_Json(objCount, 'Parse', CountJson) EQ '') then
														SRP_Json(objMonaMetricCountJsonArray, 'Add', objCount)
														SRP_Json(objCount, 'Release')
														CountRequests<-1> = MonaQueueId
														LogData<1>         = OConv(Datetime(), 'DT/^S')
														LogData<2>         = 'Successfully added MONA_QUEUE ':MonaQueueId:' to objMonaMetricCountJsonArray.'
														Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)																		
													end else
														ErrorMsg = 'Error in ':Service:' service. Error parsing CountJson json.'
													end
												end else
													ErrorMsg = 'Error in ':Service:' service. Error message: ':Error_Services('GetMessage')
												end																													
											Case Otherwise$
												// Invalid request
												InvalidRequests<-1> = MonaQueueId
												LogData<1>          = OConv(Datetime(), 'DT/^S')
												LogData<2>          = 'Encountered invalid MONA_QUEUE ':MonaQueueId:' request. Marking request for deletion.'
												Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)																
										End Case
									end else
										ErrorMsg   = 'Error in ':Service:' service. Error reading MONA_QUEUE ':MonaQueueId:'.'
										LogData<1> = OConv(Datetime(), 'DT/^S')
										LogData<2> = 'Error reading MONA_QUEUE ':MonaQueueId:' request.'
										Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)											
									end
								Repeat
								
								GoSub ClearCursors
								
								// Send requests and remove them from the queue
								If ErrorMsg EQ '' then 
									StatusArraySize = SRP_Json(objMonaStatusJsonArray, "GetCount")
									If StatusArraySize GT 0 then
										// Send bulk status request
										MonaStatusJson = SRP_Json(objMonaStatusJsonArray, 'Stringify', 'Fast')
										LogData<1>     = OConv(Datetime(), 'DT/^S')
										LogData<2>     = 'Attempting to send bulk status request to MonInBufferedWorker API.'
										Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)
										Mona_Services('SendMonaHttpRequest', 'status/bulk', MonaStatusJson)
										If Error_Services('NoError') then
											LogData<1> = OConv(Datetime(), 'DT/^S')
											LogData<2> = 'Successfully sent bulk status request to MonInBufferedWorker API.'
											Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)														
											// Delete status requests from queue
											For each MonaStatusQueueId in StatusRequests using @FM
												Delete hMonaQueue, MonaStatusQueueId then
													LogData<1> = OConv(Datetime(), 'DT/^S')
													LogData<2> = 'Successfully deleted MONA_QUEUE ':MonaStatusQueueId:' request.'
													Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)																	
												end else
													LogData<1> = OConv(Datetime(), 'DT/^S')
													LogData<2> = 'Error in ':Service:' service. Error deleting MONA_QUEUE ':MonaStatusQueueId:'.'
													Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)																	
												end
											Next MonaStatusQueueId
										end else
											ErrorMsg   = Error_Services('GetMessage')
											LogData<1> = OConv(Datetime(), 'DT/^S')
											LogData<2> = 'Failed to send bulk status request to MonInBufferedWorker API. Error message: ':ErrorMsg
											Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)														
										end
									end else
										LogData<1> = OConv(Datetime(), 'DT/^S')
										LogData<2> = 'No status requests to send to MonInBufferedWorker API.'
										Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)													
									end
									
									AverageArraySize = SRP_Json(objMonaMetricAvgJsonArray, "GetCount")
									If AverageArraySize GT 0 then
										// Send bulk average request
										MonaMetricAvgJson = SRP_Json(objMonaMetricAvgJsonArray, 'Stringify', 'Fast')
										LogData<1>        = OConv(Datetime(), 'DT/^S')
										LogData<2>        = 'Attempting to send bulk average request to MonInBufferedWorker API.'
										Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)														
										Mona_Services('SendMonaHttpRequest', 'average/bulk', MonaMetricAvgJson)
										If Error_Services('NoError') then
											LogData<1> = OConv(Datetime(), 'DT/^S')
											LogData<2> = 'Successfully sent bulk average request to MonInBufferedWorker API.'
											Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)															
											// Delete average requests from queue
											For each MonaAverageQueueId in AverageRequests using @FM
												Delete hMonaQueue, MonaAverageQueueId then
													LogData<1> = OConv(Datetime(), 'DT/^S')
													LogData<2> = 'Successfully deleted MONA_QUEUE ':MonaAverageQueueId:' request.'
													Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)																	
												end else
													LogData<1> = OConv(Datetime(), 'DT/^S')
													LogData<2> = 'Error in ':Service:' service. Error deleting MONA_QUEUE ':MonaAverageQueueId:'.'
													Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)																
												end
											Next MonaAverageQueueId													
										end	else
											ErrorMsg   = Error_Services('GetMessage')
											LogData<1> = OConv(Datetime(), 'DT/^S')
											LogData<2> = 'Failed to send bulk average request to MonInBufferedWorker API. Error message: ':ErrorMsg
											Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)															
										end
									end else
										LogData<1> = OConv(Datetime(), 'DT/^S')
										LogData<2> = 'No average requests to send to MonInBufferedWorker API.'
										Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)														
									end
									
									CountArraySize = SRP_Json(objMonaMetricCountJsonArray, "GetCount")
									If CountArraySize GT 0 then
										// Send bulk count request
										MonaMetricCountJson = SRP_Json(objMonaMetricCountJsonArray, 'Stringify', 'Fast')
										LogData<1>          = OConv(Datetime(), 'DT/^S')
										LogData<2>          = 'Attempting to send bulk count request to MonInBufferedWorker API.'
										Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)														
										Mona_Services('SendMonaHttpRequest', 'count/bulk', MonaMetricCountJson)
										If Error_Services('NoError') then
											LogData<1> = OConv(Datetime(), 'DT/^S')
											LogData<2> = 'Successfully sent bulk count request to MonInBufferedWorker API.'
											Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)																
											// Delete count requests from queue
											For each MonaCountQueueId in CountRequests using @FM
												Delete hMonaQueue, MonaCountQueueId then
													LogData<1> = OConv(Datetime(), 'DT/^S')
													LogData<2> = 'Successfully deleted MONA_QUEUE ':MonaCountQueueId:' request.'
													Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)																	
												end else
													LogData<1> = OConv(Datetime(), 'DT/^S')
													LogData<2> = 'Error in ':Service:' service. Error deleting MONA_QUEUE ':MonaCountQueueId:'.'
													Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)																	
												end
											Next MonaCountQueueId														
										end	else
											ErrorMsg   = Error_Services('GetMessage')
											LogData<1> = OConv(Datetime(), 'DT/^S')
											LogData<2> = 'Failed to send bulk count request to MonInBufferedWorker API. Error message: ':ErrorMsg
											Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)															
										end
									end else
										LogData<1> = OConv(Datetime(), 'DT/^S')
										LogData<2> = 'No count requests to send to MonInBufferedWorker API.'
										Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)													
									end
									
									If InvalidRequests NE '' then
										For each InvalidRequestQueueId in InvalidRequests using @FM
											Delete hMonaQueue, InvalidRequestQueueId then
												LogData<1> = OConv(Datetime(), 'DT/^S')
												LogData<2> = 'Successfully deleted invalid MONA_QUEUE ':InvalidRequestQueueId:' request.'
												Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)															
											end else
												LogData<1>  = OConv(Datetime(), 'DT/^S')
												LogData<2>  = 'Error in ':Service:' service. Error deleting invalid MONA_QUEUE ':InvalidRequestQueueId:' request.'
												Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)															
											end													
										Next InvalidRequestQueueId
									end
									
									LogData    = ''
									LogData<1> = OConv(Datetime(), 'DT/^S')
									LogData<2> = 'Successfully processed ':DCount(StatusRequests, @FM): ' status requests'
									Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)
									LogData    = ''
									LogData<1> = OConv(Datetime(), 'DT/^S')
									LogData<2> = 'Successfully processed ':DCount(AverageRequests, @FM): ' average requests'
									Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)
									LogData    = ''
									LogData<1> = OConv(Datetime(), 'DT/^S')
									LogData<2> = 'Successfully processed ':DCount(CountRequests, @FM): ' count requests'
									Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)										
									
								end
							end else
								ErrorMsg = 'Error in ':Service:' service. Error initializing objMonaMetricCountJsonArray'
							end
						end else
							ErrorMsg = 'Error in ':Service:' service. Error intializing objMonaMetricAvgJsonArray.'
						end
					end else
						ErrorMsg = 'Error in ':Service:' service. Error initializing objMonaStatusJsonArray'
					end
					If (objMonaStatusJsonArray      NE '') then SRP_Json(objMonaStatusJsonArray, 'Release')
					If (objMonaMetricAvgJsonArray   NE '') then SRP_Json(objMonaMetricAvgJsonArray, 'Release')
					If (objMonaMetricCountJsonArray NE '') then SRP_Json(objMonaMetricCountJsonArray, 'Release')
				end else
					ErrorMsg = 'Error in ':Service:' service. Error opening MONA_QUEUE table.'
				end
			end else
				ErrorMsg = 'Error in ':Service:' service. NumRequests ':NumRequests:' is not a number.'
			end
		end else
			ErrorMsg = 'Error in ':Service:' service. Null NumRequests passed into service.'
		end
		
		If ErrorMsg NE '' then
			// Notify OI_SYSADMIN group
			Recipients   = ''
			SentFrom     = 'SYSTEM'
			Subject      = Service:' Error'
			Message      = OConv(Datetime(), 'DT/^S')
			Server       = Environment_Services('GetServer')
			Message<2>   = 'Error on server ':Server
			Message<3>   = 'Error message: ':ErrorMsg
			AttachWindow = ''
			AttachKey    = ''
			SendToGroup  = 'OI_SYSADMIN'
			Parms        = Recipients:@RM:SentFrom:@RM:Subject:@RM:Message:@RM:AttachWindow:@RM:AttachKey:@RM:SendToGroup
			obj_Notes('Create',Parms)			
			Error_Services('Add', ErrorMsg)
		end
		
		LogData    = ''
		LogData<1> = OConv(Datetime(), 'DT/^S')
		LogData<2> = 'End ProcessMonaQueue'
		Logging_Services('AppendLog', objMonaQueueLog, LogData, @RM, @FM)		
		
		Unlock hSysLists, ServiceKeyID else Null
	end
	
end service


Service GetMonaDatetimeFormat(InternalDtm)
	
	ErrorMsg = ''
	MonaDtm  = ''
	If (InternalDtm NE '') then
		If Num(InternalDtm) then
			Year   = SRP_Datetime("Year", InternalDtm)
			Month  = Fmt(SRP_Datetime("Month", InternalDtm), 'R(0)#2')
			Day    = Fmt(SRP_Datetime("Day", InternalDtm), 'R(0)#2')
			Hour   = Fmt(SRP_Datetime("Hour", InternalDtm), 'R(0)#2')
			Minute = Fmt(SRP_Datetime("Minute", InternalDtm), 'R(0)#2')
			Second = Fmt(SRP_Datetime("Second", InternalDtm), 'R(0)#2')
			MonaDtm = Year:'-':Month:'-':Day:'T':Hour:':':Minute:':':Second:'Z'
		end else
			ErrorMsg = 'Error in ':Service:' service. InternalDtm is not a number.'	
		end
	end else
		ErrorMsg = 'Error in ':Service:' service. Null InternalDtm passed into service.'
	end
	
	If ErrorMsg EQ '' then
		Response = MonaDtm
	end else
		Error_Services('Add', ErrorMsg)
	end
	
end service


Service SendMonaHttpRequest(RequestType=REQUEST_TYPES, RequestBodyJson)
	
	ErrorMsg = ''
	If RequestType NE '' then 
		If RequestBodyJson NE '' then
			ApiUrl         = Environment_Services("GetMonInBufferedWorkerApiUrl"):'/':RequestType
			Retries        = 3
			BackoffSeconds = 1
			IsSuccessful   = False$
			Loop
			While (IsSuccessful EQ False$ and Retries GT 0)
				WaitSeconds = (3 - Retries) * BackoffSeconds
				Delay(WaitSeconds)
				Retries = Retries - 1
				Response = Httpclient_Services('SendHTTPRequest', 'POST', ApiUrl, 'Content-Type':@VM:'application/json':@FM:'Accept':@VM:'*/*', RequestBodyJson, '', '', False$, False$, '')
				If ( (Response EQ '"Request queued for processing"') or (Response EQ '"Requests queued for processing"' ) ) then IsSuccessful = True$
			Repeat
			If (IsSuccessful EQ False$) then ErrorMsg = 'Error in ':Service:' service. Error sending HTTP request.'
		end else
			ErrorMsg = 'Error in ':Service:' service. Null RequestBodyJson passed into service'
		end
	end else
		ErrorMsg = 'Error in ':Service:' service. Null RequestType passed into service'
	end
	If ErrorMsg NE '' then Error_Services('Add', ErrorMsg)
	
end service


Service ConvertRecordToJson(MonaQueueId)
	
	ErrorMsg      = ''
	MonaQueueJson = ''
	If MonaQueueId NE '' then
		If RowExists('MONA_QUEUE', MonaQueueId) then
			MonaQueueRec = Database_Services('ReadDataRow', 'MONA_QUEUE', MonaQueueId)
			If Error_Services('NoError') then
				Begin Case
					Case ( (MonaQueueRec<MONA_QUEUE.STATUS_NAME$> NE '') and (MonaQueueRec<MONA_QUEUE.STATUS_STATE$> NE '') )
						objStatus          = ''
						If SRP_Json(objStatus, 'New', 'Object') then
							RequestDtm        = MonaQueueRec<MONA_QUEUE.REQUEST_DTM$>
							RequestDtmMonaFmt = Mona_Services('GetMonaDatetimeFormat', RequestDtm)
							If Error_Services('NoError') then 
								If MonaQueueRec<MONA_QUEUE.MONITOR_NAME$> NE '' then
									MonitorName = MonaQueueRec<MONA_QUEUE.MONITOR_NAME$>
								end else
									MonitorName = DefaultMonitorName
								end
								StatusName         = MonaQueueRec<MONA_QUEUE.STATUS_NAME$>
								StatusState        = MonaQueueRec<MONA_QUEUE.STATUS_STATE$>
								SRP_Json(objStatus, 'SetValue', 'resource', MonitorName)
								SRP_Json(objStatus, 'SetValue', 'dateTime', RequestDtmMonaFmt)
								SRP_Json(objStatus, 'SetValue', 'statusName', StatusName)
								SRP_Json(objStatus, 'SetValue', 'statusValue', StatusState)
								MonaQueueJson      = SRP_Json(objStatus, 'Stringify', 'Fast')
							end else
								ErrorMsg = Error_Services('GetMessage')
							end
							SRP_Json(objStatus, 'Release')
						end
					Case ( (MonaQueueRec<MONA_QUEUE.METRIC_NAME$> NE '') and (MonaQueueRec<MONA_QUEUE.METRIC_NUMBER$> NE '') and (MonaQueueRec<MONA_QUEUE.METRIC_TYPE$> EQ 'AVERAGE') )
						objAverage = ''
						If SRP_Json(objAverage, 'New', 'Object') then
							RequestDtm        = MonaQueueRec<MONA_QUEUE.REQUEST_DTM$>
							RequestDtmMonaFmt = Mona_Services('GetMonaDatetimeFormat', RequestDtm)
							If Error_Services('NoError') then
								If MonaQueueRec<MONA_QUEUE.MONITOR_NAME$> NE '' then
									MonitorName = MonaQueueRec<MONA_QUEUE.MONITOR_NAME$>
								end else
									MonitorName = DefaultMonitorName
								end
								MetricName    = MonaQueueRec<MONA_QUEUE.METRIC_NAME$>
								MetricValue   = MonaQueueRec<MONA_QUEUE.METRIC_NUMBER$>
								SRP_Json(objAverage, 'SetValue', 'resource', MonitorName)
								SRP_Json(objAverage, 'SetValue', 'dateTime', RequestDtmMonaFmt)
								SRP_Json(objAverage, 'SetValue', 'metricName', MetricName)
								SRP_Json(objAverage, 'SetValue', 'metricValue', MetricValue)
								MonaQueueJson = SRP_Json(objAverage, 'Stringify', 'Fast')
							end else
								ErrorMsg = Error_Services('GetMessage')
							end
							SRP_Json(objAverage, 'Release')
						end														
					Case ( (MonaQueueRec<MONA_QUEUE.METRIC_NAME$> NE '') and (MonaQueueRec<MONA_QUEUE.METRIC_NUMBER$> NE '') and (MonaQueueRec<MONA_QUEUE.METRIC_TYPE$> EQ 'COUNT') )
						objCount          = ''
						If SRP_Json(objCount, 'New', 'Object') then
							RequestDtm        = MonaQueueRec<MONA_QUEUE.REQUEST_DTM$>
							RequestDtmMonaFmt = Mona_Services('GetMonaDatetimeFormat', RequestDtm)
							If Error_Services('NoError') then
								If MonaQueueRec<MONA_QUEUE.MONITOR_NAME$> NE '' then
									MonitorName = MonaQueueRec<MONA_QUEUE.MONITOR_NAME$>
								end else
									MonitorName = DefaultMonitorName
								end
								MetricName    = MonaQueueRec<MONA_QUEUE.METRIC_NAME$>
								MetricValue   = MonaQueueRec<MONA_QUEUE.METRIC_NUMBER$>
								SRP_Json(objCount, 'SetValue', 'resource', MonitorName)
								SRP_Json(objCount, 'SetValue', 'dateTime', RequestDtmMonaFmt)
								SRP_Json(objCount, 'SetValue', 'metricName', MetricName)
								SRP_Json(objCount, 'SetValue', 'metricValue', MetricValue)
								MonaQueueJson = SRP_Json(objCount, 'Stringify', 'Fast')
							end else
								ErrorMsg = Error_Services('GetMessage')
							end
							SRP_Json(objCount, 'Release')
						end																
					Case Otherwise$
						ErrorMsg = 'Error in ':Service:' service. MONA_QUEUE ':MonaQueueId:' is not a valid request.'	
				End Case				
			end else
				ErrorMsg = 'Error in ':Service:' service. Error message: ':Error_Services('GetMessage')
			end
		end else
			ErrorMsg = 'Error in ':Service:' service. MONA_QUEUE ':MonaQueueId:' does not exist.'	
		end
	end else
		ErrorMsg = 'Error in ':Service:' service. Null MonaQueueId passed into service.'
	end
	
	If ErrorMsg EQ '' then
		Response = MonaQueueJson
	end else
		Error_Services('Add', ErrorMsg)
	end
	
end service


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Internal GoSubs
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

ClearCursors:
	
	For counter = 0 to 8
		ClearSelect counter
	Next counter
	
return

