Function Reactitems_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        :   Reactitems_API

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

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

#pragma precomp SRP_PreCompiler

$insert APP_INSERTS
$insert API_SETUP
$insert HTTP_INSERTS

Declare subroutine OI_Wizard_Services, SRP_JSON, Database_Services
Declare function   React_Item_Services, SRP_JSON, 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
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


API reactItems.HEAD
API reactItems.GET
    
    QueryFields  = HTTP_Services('GetHTTPGetString')
    If IndexC(QueryFields, 'includeNullRetireDt', 1) then
        IncludeNullRetireDt = HTTP_Services('GetQueryField', 'includeNullRetireDt')
        Begin Case
            Case ( (IncludeNullRetireDt EQ 1) or (IncludeNullRetireDt EQ 0) )
                Null
            Case ( (IncludeNullRetireDt _EQC 'true') or (IncludeNullRetireDt _EQC 'yes') )
                IncludeNullRetireDt = True$
            Case ( (IncludeNullRetireDt _EQC 'false') or (IncludeNullRetireDt _EQC 'no') )
                IncludeNullRetireDt = False$
            Case Otherwise$
                Error_Services('Add', 'Error in ':CurrentAPI:' API. Invalid value "':IncludeNullRetireDt:'" passed in for includeNullRetireDt.')
        End Case
    end else
        IncludeNullRetireDt = ''
    end    
    
    If Error_Services('NoError') then
        If IndexC(QueryFields, 'showAllDetails', 1) then
            ShowAllDetails = HTTP_Services('GetQueryField', 'showAllDetails')
            Begin Case
                Case ( (ShowAllDetails EQ 1) or (ShowAllDetails EQ 0) )
                    Null                
                Case ( (ShowAllDetails _EQC 'true') or (ShowAllDetails _EQC 'yes') )
                    ShowAllDetails = True$
                Case ( (ShowAllDetails _EQC 'false') or (ShowAllDetails _EQC 'no') )
                    ShowAllDetails = False$
                Case Otherwise$
                    Error_Services('Add', 'Error in ':CurrentAPI:' API. Invalid value "':ShowAllDetails:'" passed in for showAllDetails.')
            End Case
        end else
            ShowAllDetails = False$
        end            
        
        If Error_Services('NoError') then
            If IndexC(QueryFields, 'currStatus', 1) then
                CurrStatus = HTTP_Services('GetQueryField', 'currStatus')
            end else
                CurrStatus = ''
            end
            If IndexC(QueryFields, 'riType', 1) then
                RIType = HTTP_Services('GetQueryField', 'riType')
            end else
                RIType = ''
            end
            If IndexC(QueryFields, 'entryDtStart', 1) then
                EntryDtStart = HTTP_Services('GetQueryField', 'entryDtStart')
            end else
                EntryDtStart = ''
            end
            If IndexC(QueryFields, 'entryDtEnd', 1) then
                EntryDtEnd = HTTP_Services('GetQueryField', 'entryDtEnd')
            end else
                EntryDtEnd = ''
            end
            If IndexC(QueryFields, 'retireDtStart', 1) then
                RetireDtStart = HTTP_Services('GetQueryField', 'retireDtStart')
            end else
                RetireDtStart = ''
            end
            If IndexC(QueryFields, 'retireDtEnd', 1) then
                RetireDtEnd = HTTP_Services('GetQueryField', 'retireDtEnd')
            end else
                RetireDtEnd = ''
            end
            
            StatusCode = 200
            GoSub CreateHALCollection
        end else
            HTTP_Services('SetResponseStatus', 400, Error_Services("GetMessage"))
        end
    end else
        HTTP_Services('SetResponseStatus', 400, Error_Services("GetMessage"))
    end
    
end api


API reactItems.ID.GET

    StatusCode = 200
    GoSub CreateHALItem

end api


API reactItems.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.
            JSON          = HTTP_Services('DecodePercentString', Body)
            ParseResponse = SRP_JSON(hJSON, 'PARSE', JSON)
            If (ParseResponse EQ '') then
                KeyID  = ''
                Record = React_Item_Services('ConvertJSONToRecord', JSON)
                If Error_Services('NoError') then
                    ReactItemID = React_Item_Services('CreateReactItem', Record)
                end
                SRP_JSON(hJSON, 'Release')
                If Error_Services('NoError') then
                    StatusCode  = 201
                    Message     = 'React Item Created'
                    GoSub CreateHalItem
                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
            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


API ReactItems.ID.PUT
    
    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.
            JSON          = HTTP_Services('DecodePercentString', Body)
            ParseResponse = SRP_JSON(hJSON, 'PARSE', JSON)
            If (ParseResponse EQ '') then
                SRP_JSON(hJSON, 'Release')
                KeyID  = EndpointSegment
                Record = React_Item_Services('ConvertJSONToRecord', JSON)
                If KeyID NE '' and Record NE '' then
                    Database_Services('WriteDataRow', 'REACT_ITEM', KeyID, Record)
                end
                If Error_Services('NoError') then
                    StatusCode  = 200
                    Message     = 'React Item Updated'
                    GoSub CreateHalItem
                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
            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


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


//----------------------------------------------------------------------------------------------------------------------
// CreateHALTemplate
//
// Creates a HAL+JSON template for creating a new record.
//----------------------------------------------------------------------------------------------------------------------
CreateHALTemplate:
    
    ReactItemJSON = React_Item_Services('GetReactItemTemplateJSON')

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


//----------------------------------------------------------------------------------------------------------------------
// CreateHALItem
//
// Creates a HAL+JSON object based on the OpenInsight data row representation of the scan.
//----------------------------------------------------------------------------------------------------------------------
CreateHALItem:
    
    If Unassigned(ReactItemID) then ReactItemID = EndpointSegment
    ReactItemJSON = React_Item_Services('ConvertRecordToJSON', ReactItemID, '', FullEndpointURL)

    If Error_Services('NoError') then
        HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
        HTTP_Services('SetResponseBody', ReactItemJSON, 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
//
// Creates a HAL+JSON collection based on OpenInsight data row representations.
//----------------------------------------------------------------------------------------------------------------------
CreateHALCollection:
    
    JSONCollection = ''
    Abort          = False$
    ReactItems     = React_Item_Services('GetReactItems', RIType, CurrStatus, EntryDtStart, EntryDtEnd, RetireDtStart, RetireDtEnd, IncludeNullRetireDt)
    
    If ReactItems NE '' then
        If SRP_JSON(hJSONCollection, 'New', 'Object') then
            If SRP_JSON(hReactItemsArray, 'New', 'Array') then
                For each ReactItemID in ReactItems using @VM setting vPos
                    If Not(ShowAllDetails) then
                        ReactItemJSON = React_Item_Services('ConvertRecordToJSONQuick', ReactItemID, '', FullEndpointURLNoQuery:'/':ReactItemID)
                    end else
                       ReactItemJSON = React_Item_Services('ConvertRecordToJSON', ReactItemID, '', FullEndpointURLNoQuery:'/':ReactItemID) 
                    end
                    If Error_Services('NoError') then
                        If (SRP_JSON(hReactItem, 'Parse', ReactItemJSON) EQ '') then
                            SRP_JSON(hReactItemsArray, 'Add', hReactItem)
                            SRP_JSON(hReactItem, 'Release')
                        end
                    end else
                        Abort   = True$
                    end
                Until Abort
                Next ReactItemID
                If Abort EQ False$ then
                    SRP_JSON(hJSONCollection, 'Set', 'reactItems', hReactItemsArray)
                end
                SRP_JSON(hReactItemsArray, 'Release')
            end
            JSONCollection        = SRP_JSON(hJSONCollection, 'Stringify', 'Styled')
            SRP_JSON(hJSONCollection, 'Release')
        end
    end else
        Message = 'No reactItems found!'
    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

