Function ReactorLogs_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        :   ReactorLogs_API

    Description :   API logic for the ReactorLogs 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 ReactorLogs[.ID.[<Property>]]
                                    - HTTPMethod can be any valid HTTP method, e.g., GET, POST, PUT, DELETE, etc.
                                Examples:
                                    - ReactorLogs.POST
                                    - ReactorLogs.ID.PUT
                                    - ReactorLogs.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/08/22    xxx     Original programmer.

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

#pragma precomp SRP_PreCompiler

$insert APP_INSERTS
$insert API_SETUP
$insert HTTP_INSERTS
$insert REACTOR_LOG_EQUATES
$insert OI_WIZARD_EQUATES

Declare function   Reactor_Log_Services, OI_Wizard_Services, MemberOf, Nica_Orders_Services
Declare subroutine Database_Services, Reactor_Log_Services, Override_Log_Services, Nica_Orders_Services

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

Return Response OR ''


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


// Endpoint to return a reactor log object
API ReactorLogs.ID.GET
    
    // Return JSON payload containing Reactor Log record details
    StatusCode = 200
    GoSub CreateHALItem

end api


// Endpoint to update a reactor log object
API ReactorLogs.ID.PUT
    
    OIWizardID = ''
    Cookies    = HTTP_Services('GetHTTPCookie')
    For each Cookie in Cookies using ';'
        Key = Trim(Field(Cookie, '=', 1))
        If Key EQ 'sessionID' then
            OIWizardID = Field(Cookie, '=', 2)
        end
        If Key EQ 'userID' then
            CurrUser = Field(Cookie, '=', 2)
        end
    Next Cookie
    
    ValidSession = OI_Wizard_Services('ValidateSession', OIWizardID)

    If ValidSession then
        RLKey = EndpointSegment
        Body = HTTP_Services('GetHTTPPostString')
        If Body NE '' then
            // The POST string will have been encoded so use percent (URL) decoding.
            ReactorLogJSON = HTTP_Services('DecodePercentString', Body)
            hReactorLog    = ''
            ParseResponse  = SRP_JSON(hReactorLog, 'PARSE', ReactorLogJSON)
            If (ParseResponse EQ '') then
                NewReactorLogRec = Reactor_Log_Services('ConvertJSONToRecord', ReactorLogJSON)
                If Error_Services('NoError') then
                    // Get original signature value to check if we need to invoke signature service.
                    OrigSig = Xlate('REACTOR_LOG', RLKey, 'TECH_SIG', 'X')
                    // Update the record
                    Reactor_Log_Services('SaveReactorLogRecord', RLKey, NewReactorLogRec)
                    If Error_Services('NoError') then
                        // Get new signature value
                        NewSig  = NewReactorLogRec<REACTOR_LOG_TECH_SIG$>
                        If ( (OrigSig EQ '') and (NewSig NE '') ) then
                            Reactor_Log_Services('SignReactorLog', RLKey, NewSig)
                            If Error_Services('NoError') then
                                StatusCode = 200
                                Message    = 'Reactor Log record updated and signed'
                                GoSub CreateHALItem
                            end else
                                ErrorMsg = Error_Services('GetMessage')
                                If IndexC(ErrorMsg, 'NICA order(s)', 1) then
                                	// NICA override required, so return specific status code and override information.
                                	HTTP_Services('SetResponseStatus', 300, ErrorMsg)
                                	ResBody = '{"username":"","password":"","groups":["SUPERVISOR","MAINTENANCE"]}'
                                	HTTP_Services('SetResponseBody', ResBody, False$, 'application/hal+json')
                                end else
                                	HTTP_Services('SetResponseStatus', 500, 'Error in the ' : CurrentAPI : ' API. Message: ': ErrorMsg)
                                end
                                Reactor_Log_Services('ClearSignature', RLKey)
                            end
                        end else
                            StatusCode = 200
                            Message    = 'Reactor Log record updated.'
                            GoSub CreateHALItem
                        end
                    end else
                        ErrorMsg = Error_Services('GetMessage')
                        HTTP_Services('SetResponseStatus', 500, 'Error in the ' : CurrentAPI : ' API. Message: ': ErrorMsg)
                    end
                end else
                    ErrorMsg = Error_Services('GetMessage')
                    HTTP_Services('SetResponseStatus', 500, 'Error in the ' : CurrentAPI : ' API. Message: ': ErrorMsg)
                end
            end else
                HTTP_Services('SetResponseStatus', 400, 'Unable to parse the JSON data from the request.')
            end
        end else
            HTTP_Services('SetResponseStatus', 400, 'JSON object is missing in the body of the request.')
        end
    end else
        HTTP_Services('SetResponseStatus', 500, 'Invalid session. Reauthentication required.')
    end

end api


API ReactorLogs.ID.nicaOverride.POST
	
	OIWizardID = ''
    Cookies    = HTTP_Services('GetHTTPCookie')
    For each Cookie in Cookies using ';'
        Key = Trim(Field(Cookie, '=', 1))
        If Key EQ 'sessionID' then
            OIWizardID = Field(Cookie, '=', 2)
        end
        If Key EQ 'userID' then
            CurrUser = Field(Cookie, '=', 2)
        end
    Next Cookie
    
    ValidSession = OI_Wizard_Services('ValidateSession', OIWizardID)

    If ValidSession then
    	OverrideUser   = Xlate('OI_WIZARD', OIWizardID, OI_WIZARD.EMPLOYEE_ID$, 'X')
    	OverrideGroups = 'SUPERVISOR,MAINTENANCE'
    	If RowExists('LSL_USERS', OverrideUser) then
    		If ( MemberOf(OverrideUser, 'SUPERVISOR') or MemberOf(OverrideUser, 'MAINTENANCE') ) then
    			RLKey = ParentSegment
				If RowExists('REACTOR_LOG', RLKey) then
					// Parse out override comment from body
					Body = HTTP_Services('GetHTTPPostString')
					If Body NE '' then
						// The POST string will have been encoded so use percent (URL) decoding.
						ReactorLogJSON = HTTP_Services('DecodePercentString', Body)
						hReactorLog    = ''
						ParseResponse  = SRP_JSON(hReactorLog, 'PARSE', ReactorLogJSON)
						If (ParseResponse EQ '') then
							OverrideComment = SRP_JSON(hReactorLog, 'GetValue', 'overrideComment')
							SRP_JSON(hReactorLog, 'Release')
							If OverrideComment NE '' then
								Override_Log_Services('Create', 'REACTOR_LOG', RLKey, OverrideUser, OverrideComment, 'REACTOR_LOG_PM', '')
								If Error_Services('NoError') then 
									// Cancel all ReactorLog NICA Orders
									ActiveRlNicaOrderIds = Nica_Orders_Services('GetActiveOrders', 'REACTOR_LOG', RLKey)
									If ActiveRlNicaOrderIds NE '' then
										For each ActiveRlNicaOrderId in ActiveRlNicaOrderIds using @VM setting vPos
											Nica_Orders_Services('CancelOrder', ActiveRlNicaOrderId)
										Until Error_Services('HasError')
										Next ActiveRlNicaOrderId
									end
									If Error_Services('NoError') then
										HTTP_Services('SetResponseStatus', 200, 'Nica orders canceled for REACTOR_LOG "':RLKey:'".')
									end
								end else
									Http_Services('SetResponseStatus', 500, Error_Services('GetMessage'))
								end
							end else
								HTTP_Services('SetResponseStatus', 400, 'No override comment passed in!')
							end
						end else
							HTTP_Services('SetResponseStatus', 400, 'Unable to parse the JSON data from the request.')
						end
					end else
						HTTP_Services('SetResponseStatus', 400, 'JSON object is missing in the body of the request.')
					end
				end else
					HTTP_Services('SetResponseStatus', 500, 'REACTOR_LOG "':RLKey:'" does not exist!')
				end
    		end else
    			HTTP_Services('SetResponseStatus', 500, 'User is not a member of SUPERVISOR or MAINTENANCE groups.')
    		end
    	end else
    		HTTP_Services('SetResponseStatus', 500, 'User "':OverrideUser:'" does not exist!.')
    	end

    end else
        HTTP_Services('SetResponseStatus', 500, 'Invalid session. Reauthentication required.')
    end
	
end api

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


//----------------------------------------------------------------------------------------------------------------------
// CreateHALItem
//
// Creates a HAL+JSON object based on the OpenInsight data row representation of the scan.
//----------------------------------------------------------------------------------------------------------------------
CreateHALItem:
    
    RLKey          = EndpointSegment
    ReactorLogsJSON = Reactor_Log_Services('ConvertRecordToJSON', RLKey, '', FullEndpointURL)

    If Error_Services('NoError') then
        HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
        HTTP_Services('SetResponseBody', ReactorLogsJSON, False$, 'application/hal+json')
        If Assigned(Message) then
            HTTP_Services('SetResponseStatus', StatusCode, Message)
        end else
            HTTP_Services('SetResponseStatus', StatusCode)
        end
    end else
        Message = Error_Services('GetMessage')          
        HTTP_Services('SetResponseStatus', 500, 'Error in the ' : CurrentAPI : ' API. Message: ': Message)
    end

return


API reactorlogs.ID.nicaoverride.PUT

    HTTP_Resource_Services('LoremIpsum')

end api


