Function HTTP_Metrology_Services(RemainingURL)

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

    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        :   HTTP_Metrology_Services

    Description :   Handler program for the HTTP Metrology service module.

    Notes       :   All HTTP web services should include the HTTP_SERVICE_SETUP insert. This will provide several useful
                    variables:

                        APIURL                  - The base URL for the API entry point (e.g., api.mysite.com/v1).
                        FullEndPointURL         - The URL submitted by the client.
                        HTTPMethod              - The HTTP Method (Verb) submitted by the client (e.g., GET, POST, etc.)
                        SelfURL                 - The URL path representing the current service.
                        NextSegment             - The URL segment immediately following the SelfURL (if any). This
                                                  could contain the name of the next service or it could contain the
                                                  Item ID for the current service (aka resource).
                        CurrentServiceHandler   - The name of the currently running BASIC+ stored procedure.

    Parameters  :
        RemainingURL    [in] -- The remaining portion of the URL that follows the URL that launched this current
                                service. This information is used in the HTTP_SERVICE_SETUP insert to populate other
                                useful variables (see Notes above).
        Response       [out] -- Response to be sent back to the Controller (HTTP_MCP) or requesting procedure

    Metadata    :
        @@DEFINE_SERVICES_SIGNATURE(@SERVICE, RemainingURL)
        @@DEFINE_UNQUOTED_OPTIONS BOOLEAN(True$, False$)

    History     :   (Date, Initials, Notes)
        08/19/16    dmb     Original programmer. - [IREPIOI-8]

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

$insert APP_INSERTS
$insert HTTP_SERVICE_SETUP
$insert HTTP_INSERTS

Declare subroutine  RList
Declare function    Metrology_Services

ValidMethod     = True$ ; // Assume the HTTP method is valid until proven otherwise.
HasGetString    = HTTP_Services('GetHTTPGetString') NE ''

// Some methods are restricted to authorized users only. Get their security level for cross-checking later.
Username    = Memory_Services('GetValue', 'Username')
Security    = Xlate('USERS', Username, 'ACCESS_LEVEL', 'X')

Begin Case
    Case RemainingURL _EQC ''
        // This means the URL ends with /metrology.
        SelfURL = HTTP_Services('GetSelfURL')

        Begin Case
            Case HTTPMethod _EQC 'OPTIONS'  ;   GoSub Options
            Case HTTPMethod _EQC 'POST'     ;   GoSub Post
            Case Otherwise$                 ;   ValidMethod = False$
        End Case

    Case Otherwise$
        HTTP_Services('SetResponseStatus', 404, NextSegment : ' is not a valid service request within the ' : CurrentServiceHandler : ' module.')
End Case

If Not(ValidMethod) then
    HTTP_Services('SetResponseStatus', 405, HTTPMethod : ' is not valid for this service.')

    // These services are always allowed.
    HTTP_Services('SetResponseHeaderField', 'Allow', 'GET', True$)
    HTTP_Services('SetResponseHeaderField', 'Allow', 'OPTIONS', True$)

    // These services are only allowed if the service is for a specific item resource.
    If Len(NextSegment) then
        HTTP_Services('SetResponseHeaderField', 'Allow', 'POST', True$)
        HTTP_Services('SetResponseHeaderField', 'Allow', 'DELETE', True$)
    end

    If Not(HasGetString) AND NextSegment _EQC '' then
        HTTP_Services('SetResponseHeaderField', 'Allow', 'POST', True$)
    end
end

If Assigned(Response) else Response = ''

Return Response


//----------------------------------------------------------------------------------------------------------------------
// Options
//
// @@DEFINE_SERVICE(Options)
//
// Sets the appropriate response header fields for an OPTIONS request.
//----------------------------------------------------------------------------------------------------------------------
Options:
    HTTP_Services('SetResponseHeaderField', 'Access-Control-Allow-Headers', 'authorization', True$)
    HTTP_Services('SetResponseHeaderField', 'Access-Control-Allow-Headers', 'x-authorization', True$)
    HTTP_Services('SetResponseHeaderField', 'Access-Control-Max-Age', 1728000)

    HTTP_Services('SetResponseHeaderField', 'Allow', 'OPTIONS', True$)
    HTTP_Services('SetResponseHeaderField', 'Allow', 'POST', True$)
return


//----------------------------------------------------------------------------------------------------------------------
// Post
//
// @@DEFINE_SERVICE(Post)
//
// Attempts to create the resource.
//----------------------------------------------------------------------------------------------------------------------
Post:
	Body	= HTTP_Services('GetHTTPPostString')
	Body	= HTTP_Services('DecodePercentString', Body)
    // This is to allow a developer to capture the request and response in text files for external inspection.
    CapturePath     = HTTP_Services('GetCapturePath')
    Declare function RTI_OS_Directory
    If RTI_OS_Directory('EXISTS', CapturePath) EQ True$ then
        FileTimeStamp       = Oconv(Date(), 'DJS-') : '_' : Oconv(Time(), 'MTS-')
        BodyFileName        = 'Body_@_' : FileTimeStamp : '.txt'
        OSWrite Body        to CapturePath : '\' : BodyFileName
    end

    Success = Metrology_Services('ImportMetrologyRunData', Body)

    If Success then
        HTTP_Services('SetResponseStatus', 204, 'Metrology run data was successfully imported.')
        ResponseBody    = '{"status":"204","description":"Metrology run data was successfully imported."}'
        HTTP_Services('SetResponseBody', ResponseBody, False$, 'text/json')
    end else
        HTTP_Services('SetResponseStatus', 500, 'Metrology run data was unsuccessfully imported.')
        ResponseBody    = '{"status":"500","description":"Metrology run data was unsuccessfully imported."}'
        HTTP_Services('SetResponseBody', ResponseBody, False$, 'text/json')
    end
* 	Debug
return

