Function Wo_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        :   Wo_API

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

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

#pragma precomp SRP_PreCompiler

Declare function Environment_Services, SRP_Datetime, Logging_Services, Work_Order_Services
Declare Subroutine Btree.Extract, Logging_Services, Http_Services

$insert APP_INSERTS
$insert API_SETUP
$insert HTTP_INSERTS

LogDate         = Oconv(Date(), 'D4/')
LogTime         = Oconv(Time(), 'MTS')
LogPath         = Environment_Services('GetApplicationRootPath') : '\LogFiles\API\Materials\WO'
LogFileName     = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' API.csv'
Headers         = 'Logging DTM':@FM:'Method':@FM:'URL':@FM:'Response Code':@FM:'Response Message'
ObjLog          = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, Comma$, Headers, '', False$, False$)
LoggingDTM      = LogDate : ' ' : LogTime
ResponseCode    = ''
ResponseMessage = ''
LogData         = ''
GoToAPI else
    // The specific resource endpoint doesn't have a API handler yet.
    ResponseCode    = 204
    ResponseMessage = 'This is a valid endpoint but a web API handler has not yet been created.'
    LogData<1>      = OCONV(SRP_Datetime('Now', 0), 'DT')
    LogData<2>      = HTTPMethod
    LogData<3>      = FullEndpointURL
    LogData<4>      = ResponseCode
    LogData<5>      = ResponseMessage
    Logging_Services('AppendLog', ObjLog, LogData, @RM, @FM)
    HTTP_Services('SetResponseStatus', ResponseCode, ResponseMessage)
end

Return Response OR ''


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


API wo.HEAD
API wo.GET

    HTTP_Resource_Services('LoremIpsum')

end api


API wo.ID.HEAD
API wo.ID.GET

    GoSub CreateHALItem

end api

CreateHALItem:
    ResponseCode = 200
    MaterialKey  = EndpointSegment
    WOLogKey     = ''
    Swap '-' with '.' in MaterialKey
    IF RowExists('WO_LOG', MaterialKey) then
        //It is a WO_LOG Key
        WOLogKey = MaterialKey
    end else
        table = "WO_LOG"
        Open "DICT ":table To @DICT Else
            ResponseCode    = 500
            ResponseMessage = "Couldn't open WO_LOG table to read."
            HTTP_Services('SetResponseStatus', ResponseCode, 'Error in the ' : CurrentAPI : ' API. Message: ': ResponseMessage) 
        End
        IF ResponseCode NE 500 then
            Column          = "PROD_ORD_NO"
            data1           = MaterialKey
            search_criteria = column:@VM:data1:@FM
            keylist         = ""
            option          = ""
            flag            = ""
            Btree.Extract(search_criteria, table, @DICT, keylist, option, flag)
            IF DCount(keylist, @VM) then
                //It's a PROD_ORD_NO
                WOLogKey = keylist<1,1>
            end 
        end
        
    end
    IF WOLogKey NE '' then
        JSON         = Work_Order_Services('ConvertRecordToJSON', WOLogKey, '', FullEndpointURL)
    end else
        IF ResponseCode NE 500 then
            ResponseCode    = 406
            ResponseMessage = 'No WO found based on the search criteria provided.'
            HTTP_Services('SetResponseStatus', ResponseCode, ResponseMessage)
        end
    end
    LogData<1> = OCONV(SRP_Datetime('Now', 0), 'DT')
    LogData<2> = HTTPMethod
    LogData<3> = FullEndpointURL
    LogData<4> = ResponseCode
    LogData<5> = ResponseMessage
    Logging_Services('AppendLog', ObjLog, LogData, @RM, @FM)
    If Error_Services('NoError') then
        HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
        HTTP_Services('SetResponseBody', JSON, False$, 'application/hal+json')
        If Assigned(Message) then
            HTTP_Services('SetResponseStatus', ResponseCode, Message)
        end else
            HTTP_Services('SetResponseStatus', ResponseCode)
        end
    end else
        Message = Error_Services('GetMessage')          
        HTTP_Services('SetResponseStatus', 500, 'Error in the ' : CurrentAPI : ' API. Message: ': Message)
    end
return

