Function Returntofab_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        :   Returntofab_API

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

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

#pragma precomp SRP_PreCompiler

Declare function OI_Wizard_Services, Return_To_Fab_Services, Database_Services, Labeling_Services
Declare subroutine Return_To_Fab_Services

$insert APP_INSERTS
$insert API_SETUP
$insert HTTP_INSERTS
$Insert OI_WIZARD_EQUATES

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 returntofab.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
        Body = HTTP_Services('GetHTTPPostString')
        If Body NE '' then
            RTFCreateJson = HTTP_Services('DecodePercentString', Body)
            ParseResponse = SRP_JSON(hRTFCreateJson, 'PARSE', RTFCreateJson)
            If (ParseResponse EQ '') then
                UserId   = Xlate('OI_WIZARD', OIWizardID, 'EMPLOYEE_ID', 'X')
                CassId   = SRP_JSON(hRTFCreateJson, 'GetValue', 'cassId')
                SRP_JSON(hRTFCreateJson, 'Release')
                NewRTFId = Return_To_Fab_Services('CreateReturnToFabRecord', CassId, UserId)
                If Error_Services('NoError') AND NewRTFId NE '' then
                    RTFJson = Return_To_Fab_Services('ConvertReturnToFabRecordToJSON', NewRTFId)
                    If Error_Services('NoError') then
                        HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
                        HTTP_Services('SetResponseBody', RTFJson, False$, 'application/hal+json')
                        If Assigned(Message) then
                            HTTP_Services('SetResponseStatus', 201, Message)
                        end else
                            HTTP_Services('SetResponseStatus', 201)
                        end
                    end else
                        HTTP_Services('SetResponseStatus', 400, Error_Services('GetMessage'))
                    end
                    
                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
            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 returntofab.ID.HEAD
API returntofab.ID.GET
    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
        UserId = Xlate('OI_WIZARD', OIWizardID, 'EMPLOYEE_ID', 'X')
        RTFId  = EndpointSegment
        If Error_Services('NoError') AND RTFId NE '' then
            RTFJson = Return_To_Fab_Services('ConvertReturnToFabRecordToJSON', RTFId)
            If Error_Services('NoError') then
                HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
                HTTP_Services('SetResponseBody', RTFJson, False$, 'application/hal+json')
                If Assigned(Message) then
                    HTTP_Services('SetResponseStatus', 201, Message)
                end else
                    HTTP_Services('SetResponseStatus', 201)
                end
            end else
                
            end
            
        end else
            HTTP_Services('SetResponseStatus', 400, Error_Services('GetMessage'))
        end
    end else
        HTTP_Services('SetResponseStatus', 401, 'Invalid session. Reauthentication required.')
    end
end api


API returntofab.ID.PATCH
    // Update reactor reactor and return updated reactor object
    RTFId = EndpointSegment
    If RTFId then
        // Look for the sessionID in the cookie
        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 update a field in the reactors record
            Body = HTTP_Services('GetHTTPPostString')
            If Body NE '' then
                JSON          = HTTP_Services('DecodePercentString', Body)
                hJSON         = ''
                ParseResponse = SRP_JSON(hJSON, 'PARSE', JSON)
                If (ParseResponse EQ '') then
                    UpdateFields = SRP_Json(hJSON, "GetMembers")
                    LSLUser      = Database_Services('ReadDataColumn', 'OI_WIZARD', OIWizardID, OI_WIZARD.EMPLOYEE_ID$, True$, 0, False$)
                    for each Field in UpdateFields using @FM
                        Value = SRP_Json(hJSON, "GetValue", Field)
                        Begin Case
                            Case Field EQ "Reason"
                                Return_To_Fab_Services('SetReasonForReturn', RTFId, LSLUser, Value)
                            Case Field EQ 'EvalResultId'
                                Return_To_Fab_Services('SetEvalInfo', RTFId, LSLUser, Value)
                            Case Field EQ 'MhInitDtm'
                                Return_To_Fab_Services('SetBinToBin', RTFId, LSLUser)
                            Case Field EQ 'CompletedDtm'
                                Return_To_Fab_Services('SetFinalBinToBin', RTFId, LSLUser)
                                if Error_Services('NoError') then
                                    Return_To_Fab_Services('SetRTFCompleted', RTFId, LSLUser)
                                end else
                                    ErrorMessage = Error_Services('GetMessage')
                                    Error_Services('Add', ErrorMessage)
                                end
                            Case Field EQ 'Note'
                                Return_To_Fab_Services('AddMiscNote', RTFId, Value, LSLUser)
                            Case Otherwise$
                                Error_Services('Add', 'Error Updating ' : Field : 'field in RTF Record.')
                        End Case
                    Next Field
                    If Error_Services('NoError') then
                        StatusCode  = 200
                        Message     = 'Reactor Updated'
                        RTFJson = Return_To_Fab_Services('ConvertReturnToFabRecordToJSON', RTFId)
                        HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
                        HTTP_Services('SetResponseBody', RTFJson, False$, 'application/hal+json')
                    end else
                        HTTP_Services('SetResponseStatus', 500, Error_Services('GetMessage'))
                    end
                    SRP_JSON(hJSON, 'Release')
                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

end api


API returntofab.evaluationresultoptions.HEAD
API returntofab.evaluationresultoptions.GET
    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
        GoSub CreateResultOptionCollection
    end else
        HTTP_Services('SetResponseStatus', 401, 'Invalid session. Reauthentication required.')
    end
end api

API returntofab.reportopenforms.HEAD
API returntofab.reportopenforms.GET

    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
        UserId = Xlate('OI_WIZARD', OIWizardID, 'EMPLOYEE_ID', 'X')
        RTFId  = EndpointSegment
        If Error_Services('NoError') AND RTFId NE '' then
            RTFJson = Return_To_Fab_Services('CreateReturnToFabReportJson', True$)
            If Error_Services('NoError') then
                HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
                HTTP_Services('SetResponseBody', RTFJson, False$, 'application/hal+json')
                If Assigned(Message) then
                    HTTP_Services('SetResponseStatus', 201, Message)
                end else
                    HTTP_Services('SetResponseStatus', 201)
                end
            end else
                
            end
            
        end else
            HTTP_Services('SetResponseStatus', 400, Error_Services('GetMessage'))
        end
    end else
        HTTP_Services('SetResponseStatus', 401, 'Invalid session. Reauthentication required.')
    end

end api


API returntofab.reportallforms.HEAD
API returntofab.reportallforms.GET

    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
        UserId = Xlate('OI_WIZARD', OIWizardID, 'EMPLOYEE_ID', 'X')
        RTFId  = EndpointSegment
        If Error_Services('NoError') AND RTFId NE '' then
            RTFJson = Return_To_Fab_Services('CreateReturnToFabReportJson', False$)
            If Error_Services('NoError') then
                HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
                HTTP_Services('SetResponseBody', RTFJson, False$, 'application/hal+json')
                If Assigned(Message) then
                    HTTP_Services('SetResponseStatus', 201, Message)
                end else
                    HTTP_Services('SetResponseStatus', 201)
                end
            end else
                
            end
            
        end else
            HTTP_Services('SetResponseStatus', 400, Error_Services('GetMessage'))
        end
    end else
        HTTP_Services('SetResponseStatus', 401, 'Invalid session. Reauthentication required.')
    end

end api

//----------------------------------------------------------------------------------------------------------------------
// CreateResultOptionCollection
//
// Creates a HAL+JSON object based on OpenInsight data row representations.
//----------------------------------------------------------------------------------------------------------------------
CreateResultOptionCollection:
    
    JSONCollection    = ''
    Abort             = False$
    ResultOptions = Return_To_Fab_Services('GetReturnToFabResultOptions')
    hJSONCollection   = ''
    If SRP_JSON(hJSONCollection, 'New', 'Object') then
    	hResultOptionCollection = ''
        If SRP_JSON(hResultOptionCollection, 'New', 'Array') then
            For each ResultOptionId in ResultOptions<1> using @VM setting fPos
                hOptionJson = ''
                if SRP_JSON(hOptionJson, 'New', 'Object') then
                    SRP_JSON(hOptionJson, 'SetValue', 'ResultOptionId', ResultOptionId, 'Number')
                    SRP_JSON(hOptionJson, 'SetValue', 'ResultOptionDesc', ResultOptions<2,fPos>, 'String')
                    SRP_JSON(hResultOptionCollection, 'Add', hOptionJson)
                    SRP_JSON(hOptionJson, 'Release')
                end
            Next ResultOptionId
            SRP_JSON(hJSONCollection, 'Set', 'ResultOptions', hResultOptionCollection)
            SRP_JSON(hResultOptionCollection, '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', 201, Message)
        end else
            HTTP_Services('SetResponseStatus', 201)
        end
    end else
        Message = Error_Services('GetMessage')          
        HTTP_Services('SetResponseStatus', 500, 'Error in the ' : CurrentAPI : ' API. Message: ': Message)
    end

return


API returntofab.getreturntofablabelzpl.HEAD
API returntofab.getreturntofablabelzpl.GET
    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
        RTFId = HTTP_Services('GetQueryField', 'ReturnToFabId')
        If RTFId NE '' then
            // The POST string will have been encoded so use percent (URL) decoding.
                //Reactor_Services('CreateReactModeChange', UserID, ReactNo, Mode, ModeSubCat, ModeText)
                ZPLString = Labeling_Services('GetReturnToFabLabelZPL', RTFId) 
                If Error_Services('NoError') And ZPLString NE '' then
                    // Maybe return the corresponding reactor object with the new current mode info.
                    HTTP_Services('SetResponseStatus', 201, ZPLString)
                end else
                    HTTP_Services('SetResponseStatus', 400, Error_Services('GetMessage'))
                end
        end else
            HTTP_Services('SetResponseStatus', 400, 'RTFId was null')
        end
    end else
        HTTP_Services('SetResponseStatus', 401, 'Invalid session. Reauthentication required.')
    end
end api
