Function ReactorModes_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        :   ReactorModes_API

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

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

#pragma precomp SRP_PreCompiler

$insert APP_INSERTS
$insert API_SETUP
$insert HTTP_INSERTS

Declare function   Reactor_Services, OI_Wizard_Services, React_Mode_NG_Services, React_Mode_Ng_Services
Declare function   Oi_Wizard_Services
Declare subroutine Reactor_Services, Oi_Wizard_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 create a reactor mode object (i.e. initiate a react mode change)
API ReactorModes.POST
    OIWizardID = ''
    Cookies    = HTTP_Services('GetHTTPCookie')
    For each Cookie in Cookies using ';'
        Key = Field(Cookie, '=', 1)
        If Key EQ 'sessionID' then
            OIWizardID = Field(Cookie, '=', 2)
        end
    Next Cookie
    
    ValidSession = OI_Wizard_Services('ValidateSession', OIWizardID)

    If ValidSession then
        // Check if payload has the required information to create a react mode change record
        Body = HTTP_Services('GetHTTPPostString')
        If Body NE '' then
            // The POST string will have been encoded so use percent (URL) decoding.
            ReactModeJSON = HTTP_Services('DecodePercentString', Body)
            ParseResponse = SRP_JSON(hReactModeJSON, 'PARSE', ReactModeJSON)
            If (ParseResponse EQ '') then
                UserID     = SRP_JSON(hReactModeJSON, 'GetValue', 'userID')
                ReactNo    = SRP_JSON(hReactModeJSON, 'GetValue', 'reactNo')
                Mode       = SRP_JSON(hReactModeJSON, 'GetValue', 'mode')
                ModeSubCat = SRP_JSON(hReactModeJSON, 'GetValue', 'modeSubCat')
                ModeText   = SRP_JSON(hReactModeJSON, 'GetValue', 'modeText')
                SRP_JSON(hReactModeJSON, 'Release')
                Reactor_Services('CreateReactModeChange', UserID, ReactNo, Mode, ModeSubCat, ModeText)
                If Error_Services('NoError') then
                    // Maybe return the corresponding reactor object with the new current mode info.
                    HTTP_Services('SetResponseStatus', 201, 'Reactor Mode Change Successful')
                end else
                    HTTP_Services('SetResponseStatus', 400, Error_Services('GetMessage'))
                end
            end else
                // Error parsing JSON
                HTTP_Services('SetResponseStatus', 400, 'Unable to parse the JSON data from the request.')
            end
        end else
            // No JSON payload sent with request
            If SRP_JSON(hTemplateJSON, 'New', 'Object', 'Template') then
                SRP_JSON(hTemplateJSON, 'SetValue', 'userID', '')
                SRP_JSON(hTemplateJSON, 'SetValue', 'reactNo', '')
                SRP_JSON(hTemplateJSON, 'SetValue', 'mode', '')
                SRP_JSON(hTemplateJSON, 'SetValue', 'modeSubCat', '')
                SRP_JSON(hTemplateJSON, 'SetValue', 'modeText', '')
                JSONTemplate = SRP_JSON(hTemplateJSON, 'Stringify', 'Styled')
                SRP_JSON(hTemplateJSON, 'Release')
                HTTP_Services('SetResponseBody', JSONTemplate, False$, 'application/hal+json')
            end
            HTTP_Services('SetResponseStatus', 400, 'JSON object is missing in the body of the request.')
        end
    end else
        HTTP_Services('SetResponseStatus', 401, 'Invalid session. Reauthentication required.')
    end
    
end api


// Endpoint to get a reactor mode object
API ReactorModes.ID.HEAD
API ReactorModes.ID.GET

    RMKey = EndpointSegment

end api

API ReactorModes.GET
    Cookies = HTTP_Services('GetHTTPCookie')
    For each Cookie in Cookies using ';'
        Key = Field(Cookie, '=', 1)
        If Key EQ 'sessionID' then
            OIWizardID = Field(Cookie, '=', 2)
        end
    Next Cookie
    If Assigned(OIWizardID) then
        // Call validate session to extend session expiry
        OI_Wizard_Services('ValidateSession', OIWizardID)
        CurrUser = Xlate('OI_WIZARD', OIWizardID, 'EMPLOYEE_ID', 'X')
    end else
        CurrUser = ''
    end
    daysToReport   = Http_Services('GetQueryField', 'daysToReport')
    reactorNo      = ParentSegment
    reactModesList = React_Mode_Ng_Services('GetReactModeHistoryKeys', reactorNo, daysToReport)
    StatusCode = 200
    gosub CreateHALCollection
    
end api

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


//----------------------------------------------------------------------------------------------------------------------
// CreateHALItem
//
// Creates a HAL+JSON object based on the OpenInsight data row representation of the scan.
//----------------------------------------------------------------------------------------------------------------------
CreateHALItem:
    
    
    ReactorModeJSON = React_Mode_NG_Services('ConvertRecordToJSON', RMKey, '', FullEndpointURL)

    If Error_Services('NoError') then
        HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
        HTTP_Services('SetResponseBody', ReactorModeJSON, 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

CreateHALCollection:
    
    Abort          = False$
    If SRP_JSON(hJSONCollection, 'New', 'Object') then
        If SRP_JSON(hReactModeArray, 'New', 'Array') then
            
            For each reactMode in reactModesList using @FM setting fPos
                reactModeJSON = React_Mode_Ng_Services('ConvertRecordToJSON', reactMode,FullEndpointURL:'/':reactMode)
                If Error_Services('NoError') then
                    If SRP_JSON(hReactModeObj, 'New', 'Object') then
                        If (SRP_JSON(hReactMode, 'Parse', reactModeJSON) EQ '') then
                        
                            tempHandle = SRP_JSON(hReactMode, 'Get', 'reactorMode')
                            SRP_JSON(hReactModeObj, 'Set', 'reactorMode', tempHandle)
                            SRP_JSON(tempHandle, 'Release')
                            //SRP_JSON(hReactModeArray, 'Add', tempHandle)
                            SRP_JSON(hReactModeArray, 'Add', hReactModeObj)
                            
                            SRP_JSON(hReactMode, 'Release')
                            SRP_JSON(hReactModeObj, 'Release')
                        end
                    end
                end else
                    Abort   = True$
                end
            Until Abort
            Next reactMode
            
            If Abort EQ False$ then
                SRP_JSON(hJSONCollection, 'Set', 'reactorModes', hReactModeArray)
            end
            SRP_JSON(hReactModeArray, 'Release')
        end
        JSONCollection = SRP_JSON(hJSONCollection, 'Stringify', 'Styled')
        SRP_JSON(hJSONCollection, 'Release')
    end
    
    If Error_Services('NoError') then
        HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
        HTTP_Services('SetResponseBody', JSONCollection, 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
