Function Lot_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        :   Lot_API

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

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

#pragma precomp SRP_PreCompiler

Declare function OI_Wizard_Services, Lot_Services, Database_Services, PSN_Services, Clean_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 lot.ID.HEAD
API lot.ID.GET

    ErrorMessage = ''
    ResponseCode = ''
    ResponseMessage = ''
    Body = ''
    OIWizardID = ''
    UserId = ''
    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, OI_WIZARD.EMPLOYEE_ID$, 'X')
        LotId = EndpointSegment
        If RowExists('LOT', LotId) then
            LotJson = Lot_Services('ConvertLotRecordToJson', LotId, '', UserId)
            HTTP_Services('SetResponseBody', LotJson, False$, 'application/hal+json')
            ResponseCode = 200
        end else
            ResponseCode = 500
            ErrorMessage = 'Lot not found in database.'
        end
        
    end else
        ErrorMessage = 'Invalid session. Reauthentication required.'
        ResponseCode = 401
    end
    
    HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
    HTTP_Services('SetResponseStatus', ResponseCode, ErrorMessage)

end api


API lot.getlotbylegacylotid.HEAD
API lot.getlotbylegacylotid.GET
    
    ErrorMessage = ''
    ResponseCode = ''
    ResponseMessage = ''
    Body = ''
    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, OI_WIZARD.EMPLOYEE_ID$, 'X')
        StatusCode  = ''
        Body        = HTTP_Services('GetHTTPGetString')
        
        LegacyLotId = Http_Services('GetQueryField', 'LegacyLotId')
        LegacyLotType = Http_Services('GetQueryField', 'LegacyLotType')

        LotId = Lot_Services('GetLotIdByLegacyLotIdAndType', LegacyLotId, LegacyLotType) 
        LotJson = Lot_Services('ConvertLotRecordToJson', LotId, '', UserId)
        If Error_Services('NoError') then
            HTTP_Services('SetResponseBody', LotJson, False$, 'application/hal+json')
            ResponseCode = 200
        end else
            ErrorMessage = Error_Services('GetMessage')
            ResponseCode = 500
        end
        
    end else
        ErrorMessage = 'Invalid session. Reauthentication required.'
        ResponseCode = 401
    end
    HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
    HTTP_Services('SetResponseStatus', ResponseCode, ErrorMessage)

end api

end api


API lot.ID.getrecipeoptions.HEAD
API lot.ID.getrecipeoptions.GET

    JSONCollection = ''
    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
        LotId = EndpointSegment
        PSN = Database_Services('ReadDataColumn', 'LOT', LotId, LOT_PROD_SPEC_ID$, True$, 0, False$)
        RecipeParameters = PSN_Services('GetAllMetrologyRecipes', PSN, True$, True$, True$, True$)
        If Error_Services('NoError') then
            If Body NE '' then
                RequestJson      = HTTP_Services('DecodePercentString', Body)
                objJSONResponse = ''
                If SRP_Json(objJSONResponse, 'New', 'Object') then
                    //Available Tools
                    If SRP_Json(objCleanTools, 'New', 'Array') then
                        CleanTools = Clean_Services('GetCleanToolOptions')
                        for each CleanTool in CleanTools using @FM
                            SRP_Json(objCleanTools, 'AddValue', CleanTool, 'String')
                        Next CleanTool
                        SRP_Json(objJsonResponse, 'Set', 'CleanToolOptions', objCleanTools)
                        SRP_Json(objCleanTools, 'Release')
                    end
                    //Available Recipes
                    If SRP_Json(objCleanRecipes, 'New', 'Array') then
                        CleanRecipes = Clean_Services('GetCleanRecipeOptions')
                        for each Recipe in CleanRecipes using @VM
                            SRP_Json(objCleanRecipes, 'AddValue', Recipe, 'String')
                        Next Recipe
                        SRP_Json(objJsonResponse, 'Set', 'CleanRecipeOptions', objCleanRecipes)
                        SRP_Json(objCleanRecipes, 'Release')
                    end
                    JsonResponse = SRP_Json(objJsonResponse, 'Stringify', 'Styled')
                    SRP_Json(objJsonResponse, 'Release')
                end else
                    Error_Services('Add', 'Error when creating JSON response.')
                end
            end else
                Error_Services('Add', 'No body was sent with the request.')
            end
        end else
            ErrorMessage = Error_Services('GetMessage')
        end
        
        If Error_Services('NoError') then
            HTTP_Services('SetResponseStatus', 201, 'Success')
            HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
            HTTP_Services('SetResponseBody', JsonResponse, False$, 'application/hal+json')
        end else
            HTTP_Services('SetResponseStatus', 400, Error_Services('GetMessage'))
        end
    end else
        HTTP_Services('SetResponseStatus', 401, 'Invalid session. Reauthentication required.')
    end

end api


