FUNCTION CHANGE_LOG_SERVICES(@Service, @Params)




#pragma precomp SRP_PreCompiler
$Insert LOGICAL
$insert SERVICE_SETUP
$Insert REVDOTNETEQUATES
$Insert CHANGE_LOG_EQUATES
$Insert APP_INSERTS

EQU COMMA$ to ','

Declare function    Repository, Get_Repos_Entities, SRP_DateTime, SRP_Array, Get_Status, Set_Status, Errmsg, Datetime
Declare subroutine Set_Status, Errmsg, Error_Services, Database_Services, Btree.Extract, Logging_Services, Change_Log_Services, SRP_Json	
Declare Function Database_Services, Rti_Createguid, Logging_Services
Declare Function Environment_Services, SRP_Path, SRP_Json	

LogPath     = Environment_Services('GetApplicationRootPath') : '\LogFiles\Archive\Change_Log'
LogDate     = Oconv(Date(), 'D4/')
LogTime     = Oconv(Time(), 'MTS')
LogFileName = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' ChangeLogArchiveService.csv'
Headers     = 'Logging DTM' : @FM : 'Message' : @FM : 'Record ID' : @FM : 'Record Date'
objLogChangeLogArchive      = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, Comma$, Headers, '', False$, False$)
LoggingDTM  = LogDate : ' ' : LogTime   ; // Logging DTM

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

Service WriteChangeLog()
	hSysLists   = Database_Services('GetTableHandle', 'SYSLISTS')
	Lock hSysLists, ServiceKeyID then
		StartDateTime = Datetime()
		StartDateTime = SRP_DateTime("AddMinutes", StartDateTime, -15)
		//Pull in a list of all existing entities
		AllEntityIDs  = Get_Repos_Entities('LSL2', '', '', 0, 1, 0, '')
		EntityList    = ''
		Server = Environment_Services('GetServer')
		Environment = 'DEV'
		IF Server EQ 'MESSA005' OR Server EQ 'MESSA01EC' then Environment = 'PROD'
		For Each EntityID in AllEntityIDs using @FM
			ChangeLogRec = ''
			Set_Status(0)
			statList = ''
			Entity          = Repository('GET', EntityID)
			time = Entity<25>
			If time GE StartDateTime then
				(Application, EntityType, EntityClass, EntityName) using '*' = EntityID
				UpdatedBy        = Entity<26>
				IF entityType EQ 'STPROC' then
					NewChangeLogRecID = Rti_Createguid()
					ChangeLogRec<CHANGE_LOG_CHANGE_DTM$> = Time
					ChangeLogRec<CHANGE_LOG_APPLICATION$> = Application
					ChangeLogRec<CHANGE_LOG_ENTITY_TYPE$> = EntityType
					ChangeLogRec<CHANGE_LOG_ENTITY_CLASS$> = EntityClass
					ChangeLogRec<CHANGE_LOG_ENTITY_NAME$> = EntityName
					ChangeLogRec<CHANGE_LOG_UPDATED_BY$> = UpdatedBy
					ChangeLogRec<CHANGE_LOG_ENVIRONMENT$> = Environment
					Database_Services('WriteDataRow', 'CHANGE_LOG',NewChangeLogRecID, ChangeLogRec, True$, False$, True$)
				end	
			end
		Next EntityID
	end
	Unlock hSysLists, ServiceKeyID else Null
end service

Service GetChangeLogRecIDs(EntityName, StartDtm, EndDtm, UserId)
	//This will be the main entry point
	Table = 'CHANGE_LOG'
	Open 'DICT ':Table To @DICT then
		Query = ''
		If StartDtm NE '' then
			Query := 'CHANGE_DTM':@VM:'>=': StartDtm
		end else
			Query := 'CHANGE_DTM':@VM:'>0'; *Need a default value.
		end
		If EndDtm NE '' then
			Query<-1> = 'CHANGE_DTM':@VM:'<=': EndDtm
		end
		If EntityName NE '' then
			Query<-1> = 'ENTITY_NAME':@VM:EntityName
		end
		If UserId NE '' then
			Query<-1> = 'UPDATED_BY':@VM:UserId
		end
		KeyList = ''
		Option = ''
		Flag = ''
		Btree.Extract(Query, Table, @DICT, KeyList, Option, Flag)
		Response = KeyList
	end else
		Error_Services('Add', 'Error Opening CHANGE_LOG Dictionary')
	end
end service

Service ArchiveChangeLogRecByDate(StartDTM)
	If StartDTM NE ''  then
		Table = 'CHANGE_LOG'
		Open 'DICT ':Table To @DICT then
			Query = ''
			If StartDtm NE '' then
				Query := 'CHANGE_DTM':@VM:'<='StartDtm:@FM
			end
			KeyList = ''
			Option = ''
			Flag = ''
			Btree.Extract(Query, Table, @DICT, KeyList, Option, Flag)
			If KeyList NE '' then
				for each ChangeLogRecID in Keylist using @FM
					Change_Log_Services('ArchiveChangeLogRecById', ChangeLogRecID)
					If Error_Services('NoError') then
						Change_Log_Services('DeleteChangeLogRec', ChangeLogRecID)
					end else
						ErrMsg = Error_Services('GetMessage')
						Error_Services('Add', ErrMsg)
					end
				Next ChangeLogID
			end else
				ErrorMsg = 'No Change Log Keys found to archive.'
				LogData    = ''
				LogData<1> = LoggingDTM
				LogData<2> = ErrorMsg
				LogData<3> = ''
				LogData<4> = ''
				Logging_Services('AppendLog', objLogChangeLogArchive, LogData, @RM, @FM)
			end
		end else
			Error_Services('Add', 'Error Opening CHANGE_LOG Dictionary')
		end
	end else
		Error_Services('Add', 'Error Opening CHANGE_LOG Dictionary')
	end
	
end service

Service ArchiveChangeLogRecByID(ChangeLogRecID)
	//For now output the record to a CSV file on the HDD. Eventually right to SQL Server
	If RowExists('CHANGE_LOG', ChangeLogRecID) then
		ChangeLogRec = Database_Services('ReadDataRow', 'CHANGE_LOG', ChangeLogRecID)
		If Error_Services('NoError') then
			swap @VM with ',' in ChangeLogRec
			swap @FM with CRLF$ in ChangeLogRec
			ArchivePath = Environment_Services('GetApplicationRootPath') : '\Archive\CHANGE_LOG'
			FileName = ChangeLogRecID : '.csv'
			FullSavePath = ArchivePath : '\' : FileName
			OSWrite	ChangeLogRec To FullSavePath
			If SRP_Path('Exists', FullSavePath) then
				SuccessMsg = 'Successfully saved CHANGE_LOG archive record.'
				LogData    = ''
				LogData<1> = LoggingDTM
				LogData<2> = SuccessMsg
				LogData<3> = ChangeLogRecID
				LogData<4> = ''
				Logging_Services('AppendLog', objLogChangeLogArchive, LogData, @RM, @FM)
				Error_Services('Add', ErrorMsg)
			end else
				ErrorMsg = 'Attempt to archive CHANGE_LOG record ' : ChangeLogRecID : ' failed. Error verifying archived file.'
				LogData    = ''
				LogData<1> = LoggingDTM
				LogData<2> = ErrorMsg
				LogData<3> = ChangeLogRecID
				LogData<4> = ''
				Logging_Services('AppendLog', objLogChangeLogArchive, LogData, @RM, @FM)
				Error_Services('Add', ErrorMsg)
			end
		end else
			ErrorMsg = 'Attempt to archive CHANGE_LOG record ' : ChangeLogRecID : ' failed. Error while attempting to read record.'
			LogData    = ''
			LogData<1> = LoggingDTM
			LogData<2> = ErrorMsg
			LogData<3> = ChangeLogRecID
			LogData<4> = ''
			Logging_Services('AppendLog', objLogChangeLogArchive, LogData, @RM, @FM)
			Error_Services('Add', ErrorMsg)
		end
	end else
		ErrorMsg = 'Attempt to archive CHANGE_LOG record ' : ChangeLogRecID : ' failed. Record does not exist.'
		LogData    = ''
		LogData<1> = LoggingDTM
		LogData<2> = ErrorMsg
		LogData<3> = ChangeLogRecID
		LogData<4> = ''
		Logging_Services('AppendLog', objLogChangeLogArchive, LogData, @RM, @FM)
		Error_Services('Add', ErrorMsg)
	end
end service

Service DeleteChangeLogRec(ChangeLogRecID)
	
end service

Service ConvertRecordToJson(ChangeLogRecID)
	
	JSON = ''
	If ChangeLogRecID NE '' then
		If RowExists('CHANGE_LOG', ChangeLogRecID) then
			ChangeLogRec = Database_Services('ReadDataRow', 'CHANGE_LOG', ChangeLogRecID)
			objChangeLog = ''
			objJson = ''
			If SRP_JSON(objJson, 'New', 'Object') then
					SRP_JSON(objJson, 'SetValue', 'CHANGE_DTM', OConv(ChangeLogRec<CHANGE_LOG_CHANGE_DTM$>, 'DT'))
					SRP_JSON(objJson, 'SetValue', 'APPLICATION', ChangeLogRec<CHANGE_LOG_APPLICATION$>)
					SRP_JSON(objJson, 'SetValue', 'ENTITY_TYPE', ChangeLogRec<CHANGE_LOG_ENTITY_TYPE$>)
					SRP_JSON(objJson, 'SetValue', 'ENTITY_CLASS', ChangeLogRec<CHANGE_LOG_ENTITY_CLASS$>)
					SRP_JSON(objJson, 'SetValue', 'ENTITY_NAME', ChangeLogRec<CHANGE_LOG_ENTITY_NAME$>)
					SRP_JSON(objJson, 'SetValue', 'UPDATED_BY', ChangeLogRec<CHANGE_LOG_UPDATED_BY$>)
					SRP_JSON(objJson, 'SetValue', 'ENVIRONMENT', ChangeLogRec<CHANGE_LOG_ENVIRONMENT$>)
					SRP_JSON(objJson, 'Set', 'ChangeLogRec', objChangeLog)
					JSON = SRP_JSON(objJson, 'Stringify', 'Styled')
					SRP_JSON(objJson, 'Release')
			end else
				Error_Services('Add', 'Error in Change_Log_Services -> ConvertRecordToJson : Error Creating Json object')
			end	
		end else
			Error_Services('Add', 'Error in Change_Log_Services -> ConvertRecordToJson : Change_Log with record with ID ' : ChangeLogRecID : ' did not exist ')
		end
	end else
		Error_Services('Add', 'Error in Change_Log_Services -> ConvertRecordToJson : Null Change_Log ID passed into routine')
	end
	Response = JSON
end service



