Function Changelog_API(@API)
/***********************************************************************************************************************

    This program is proprietary and is not to be used by or disclosed to others, nor is it to be copied without written
    permission from SRP Computer Solutions, Inc.

    Name        :   Changelog_API

    Description :   API logic for the Changelog resource.

    Notes       :   All web APIs should include the API_SETUP insert. This will provide several useful variables:

                        HTTPMethod              - The HTTP Method (Verb) submitted by the client (e.g., GET, POST, etc.)
                        APIURL                  - The URL for the API entry point (e.g., api.mysite.com/v1).
                        FullEndpointURL         - The URL submitted by the client, including query params.
                        FullEndpointURLNoQuery  - The URL submitted by the client, excluding query params.
                        EndpointSegment         - The URL endpoint segment.
                        ParentURL               - The URL path preceeding the current endpoint.
                        CurrentAPI              - The name of this stored procedure.

    Parameters  :
        API             [in] -- Web API to process. Format is [APIPattern].[HTTPMethod]:
                                    - APIPattern must follow this structure Changelog[.ID.[<Property>]]
                                    - HTTPMethod can be any valid HTTP method, e.g., GET, POST, PUT, DELETE, etc.
                                Examples:
                                    - Changelog.POST
                                    - Changelog.ID.PUT
                                    - Changelog.ID.firstName.GET
        Response       [out] -- Response to be sent back to the Controller (HTTP_MCP) or requesting procedure. Web API
                                services do not rely upon anything being returned in the response. This is what the
                                various services like SetResponseBody and SetResponseStatus services are for. A response
                                value is only helpful if the developers want to use it for debug purposes.

    History     :   (Date, Initials, Notes)
        07/24/24    xxx     Original programmer.

***********************************************************************************************************************/

#pragma precomp SRP_PreCompiler

Declare function Datetime, SRP_Datetime, Change_Log_Services, Environment_Services, Logging_Services
Declare subroutine Logging_Services

$insert APP_INSERTS
$insert API_SETUP
$insert HTTP_INSERTS
EQU Comma$ to ','

LogPath     = Environment_Services('GetApplicationRootPath') : '\LogFiles\API\Admin\ChangeLog'
LogDate     = Oconv(Date(), 'D4/')
LogTime     = Oconv(Time(), 'MTS')
LogFileName = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' ChangeLogArchiveService.csv'
Headers     = 'Logging DTM' : @FM : 'From IP Address' : @FM : 'Message'
objLogChangeLogAPI      = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, Comma$, Headers, '', False$, False$)
LoggingDTM  = LogDate : ' ' : LogTime   ; // Logging DTM
RequesterIPAddr = HTTP_Services('GetHTTPRemoteAddr')

GoToAPI else
	// The specific resource endpoint doesn't have a API handler yet.
	HTTP_Services('SetResponseStatus', 200, 'This is a valid endpoint but a web API handler has not yet been created.')
end

Return Response OR ''


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Endpoint Handlers
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


API changelog.HEAD
	API changelog.GET
		StartDtm = Http_Services('GetQueryField', 'FromDatetime')
		ToDtm = Http_Services('GetQueryField', 'ToDatetime')
		
		StartDtm = IConv(StartDtm, 'DT')
		ToDtm = IConv(ToDtm, 'DT')
		
		If StartDtm EQ '' then
			StartDtm = SRP_Datetime('AddDays', Datetime(), -60)
		end
		If ToDtm EQ '' then
			ToDtm = Datetime()
		end
		
		EntityName = Http_Services('GetQueryField', 'EntityName')
		UserId = Http_Services('GetQueryField', 'UserID')
		
		ChangeLogIDs = Change_Log_Services('GetChangeLogRecIDs', EntityName, StartDtm, ToDtm, UserId)
		If Error_Services('NoError') then
			GoSub CreateHALCollection 
		end else
			ErrorMsg = Error_Services('GetMessage')
			LogData    = ''
			LogData<1> = LoggingDTM
			LogData<2> = RequesterIPAddr
			LogData<3> = ErrorMsg
			Logging_Services('AppendLog', objLogChangeLogAPI, LogData, @RM, @FM)
			HTTP_Services('SetResponseStatus', 500, 'Error Getting change log records from change_log table.')
		end
		
	end api
	
CreateHALCollection:
	hJsonCollection = ''
	hChangeLogArray = ''
	hChangeLogObj = ''
	hChangeLog = ''
	hChangeLogJson = ''
	Abort          = False$
	If SRP_JSON(hJSONCollection, 'New', 'Object') then
		If SRP_JSON(hChangeLogArray, 'New', 'Array') then
			For each ChangeLogID in ChangeLogIDs using @VM setting fPos
				//rdsJSON = Rds_Services('ConvertRecordToJSON', rds, '' ,FullEndpointURL:'/':rds)
				ChangeLogJson = Change_Log_Services('ConvertRecordToJSON', ChangeLogID)
				If Error_Services('NoError') then
					If (SRP_JSON(hChangeLog, 'Parse', ChangeLogJson) EQ '') then
						SRP_JSON(hChangeLogArray, 'Add', hChangeLog)
						SRP_JSON(hChangeLog, 'Release')
					end
				end else
					Abort   = True$
				end
			Until Abort
			Next rds
			If Abort EQ False$ then
				SRP_JSON(hJSONCollection, 'Set', 'ChangeLogRecords', hChangeLogArray)
			end
			SRP_JSON(hChangeLogArray, 'Release')
		end
		JSONCollection = SRP_JSON(hJSONCollection, 'Stringify', 'Styled')
		SRP_JSON(hJSONCollection, 'Release')
		HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
		HTTP_Services('SetResponseBody', JSONCollection, False$, 'application/hal+json')
		HTTP_Services('SetResponseStatus', 200)
	end
	
return
