Function Reports_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        :   Reports_API

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

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

#pragma precomp SRP_PreCompiler

$insert APP_INSERTS
$insert API_SETUP
$insert HTTP_INSERTS

Declare Function Report_Services, Oi_Wizard_Services, Logging_Services, Environment_Services, Test_Run_Services
Declare subroutine Report_Services, Logging_Services

LogPath         = Environment_Services('GetApplicationRootPath') : '\LogFiles\API\Reports'
LogDate         = Oconv(Date(), 'D4/')
LogTime         = Oconv(Time(), 'MTS')
LogFileName     = LogDate[7, 4] : '-' : LogDate[1, 2] : '-' : LogDate[4, 2] : ' Performance Reports.csv'
Headers     = 'Logging DTM' : @FM : 'ReportId' : @FM : 'From IP Address' : @FM : 'RequestURL' : @FM : 'Status Code' : @FM : 'Message'
objReportLog          = Logging_Services('NewLog', LogPath, LogFileName, CRLF$, ',', Headers, '', False$, False$)
LoggingDTM      = LogDate : ' ' : LogTime   ; // Logging DTM
RequesterIPAddr = HTTP_Services('GetHTTPRemoteAddr')

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 reports.ID.HEAD
API reports.ID.GET

    StatusCode = 200
    GoSub CreateHALItem

end api


API reports.ID.PUT
    
    OIWizardID = ''
    Cookies    = HTTP_Services('GetHTTPCookie')
    For each Cookie in Cookies using ';'
        Key = Trim(Field(Cookie, '=', 1))
        If Key EQ 'sessionID' then
            OIWizardID = Field(Cookie, '=', 2)
        end
        If Key EQ 'userID' then
            CurrUser = Field(Cookie, '=', 2)
        end
    Next Cookie
    
    ValidSession = OI_Wizard_Services('ValidateSession', OIWizardID)

    If ValidSession then
        StatusCode = 200
        GoSub UpdateHALItem
    end
    
end api


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


//----------------------------------------------------------------------------------------------------------------------
// CreateHALItem
//
// Creates a HAL+JSON object based on the OpenInsight data row representation of the scan.
//----------------------------------------------------------------------------------------------------------------------
CreateHALItem:
    
    ReportID   = EndpointSegment
    LogData    = ''
	LogData<1> = LoggingDTM
	LogData<2> = ReportID
	LogData<3> = RequesterIPAddr
	LogData<4> = FullEndpointURL
	LogData<5> = ''
	LogData<6> = 'Request Received'
	Logging_Services('AppendLog', objReportLog, LogData, @RM, @FM)
    Begin Case
        Case ReportID = 'makeupinventory'
    		RepJSON = Report_Services('GetMakeupInventoryReportJSON')
        Case ReportID = 'materialtrack'
            RepJSON = Report_Services('GetMaterialTrackJSON')
        Case ReportID = 'dailyperformance'
            ReportDate = Http_Services('GetQueryField', 'reportDate')
            RepJSON    = Report_Services('GetDailyPerformanceDataJSON', ReportDate)
        Case ReportID = 'DailyReactorUptime'
        	ReportStartDtm = Http_Services('GetQueryField', 'StartDate')
        	ReportEndDtm = Http_Services('GetQueryField', 'EndDate')
        	RepJSON    = Report_Services('GetDailyReactorUptimeDataJSON', ReportStartDtm, ReportEndDtm)
        Case ReportID = 'TestWaferWIPReport'
            RepJSON = Report_Services('GetOpenTestWaferLotWIPReportJson')
        Case ReportID = 'OpenNCRReport'
            RepJson = Report_Services('GetOpenNCRReportJson')
        Case ReportID = 'SLLReport'
            //Single Load Lock Report from Metrology Services
            ReportStartDtm = Http_Services('GetQueryField', 'StartDate')
        	ReportEndDtm = Http_Services('GetQueryField', 'EndDate')
        	If ReportStartDtm NE '' AND ReportEndDtm NE '' then
        	    RepJson = Report_Services('GetSLLReportJson', ReportStartDtm, ReportEndDtm)
        	end else
        	    Error_Services('Add', 'Missing parameters for report.')
        	end
            
        Case Otherwise$
            Error_Services('Add', 'Unsupported report')
    End Case

    If Error_Services('NoError') then
        HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
        HTTP_Services('SetResponseBody', RepJSON, False$, 'application/hal+json')
        If Assigned(Message) then
            HTTP_Services('SetResponseStatus', StatusCode, Message)
			LogData    = ''
			LogData<1> = LoggingDTM
			LogData<2> = ReportID
			LogData<3> = RequesterIPAddr
			LogData<4> = FullEndpointURL
			LogData<5> = StatusCode
			LogData<6> = Message
			Logging_Services('AppendLog', objReportLog, LogData, @RM, @FM)
        end else
            HTTP_Services('SetResponseStatus', StatusCode)
            LogData    = ''
			LogData<1> = LoggingDTM
			LogData<2> = ReportID
			LogData<3> = RequesterIPAddr
			LogData<4> = FullEndpointURL
			LogData<5> = StatusCode
			LogData<6> = 'Success'
			Logging_Services('AppendLog', objReportLog, LogData, @RM, @FM)
        end
    end else
        Message = Error_Services('GetMessage')
        HTTP_Services('SetResponseStatus', 500, 'Error in the ' : CurrentAPI : ' API Running ':ReportID:'. Message: ': Message)
        LogData    = ''
		LogData<1> = LoggingDTM
		LogData<2> = ReportID
		LogData<3> = RequesterIPAddr
		LogData<4> = FullEndpointURL
		LogData<5> = 500
		LogData<6> = Message
		Logging_Services('AppendLog', objReportLog, LogData, @RM, @FM)
    end

return


//----------------------------------------------------------------------------------------------------------------------
// UpdateHALItem
//
// Updates a HAL+JSON object based on the OpenInsight data row representation of the data.
//----------------------------------------------------------------------------------------------------------------------
UpdateHALItem:
    ReportID = EndpointSegment
    
    Begin Case
        Case ReportID = 'materialtrack'
			Body = HTTP_Services('GetHTTPPostString')
            If (Body NE '') then
                // The POST string will have been encoded so use percent (URL) decoding.
                RepJSON = HTTP_Services('DecodePercentString', Body)
                Report_Services('UpdateMaterialTrackData', RepJSON)
            end            
            
        Case ReportID = 'dailyperformance'
            ReportDate = Http_Services('GetQueryField', 'reportDate')
            // The resource will have been put into the POST string.
            Body    = HTTP_Services('GetHTTPPostString')
            If ( (ReportDate NE '') and (Body NE '') ) then
                // The POST string will have been encoded so use percent (URL) decoding.
                RepJSON = HTTP_Services('DecodePercentString', Body)
                Report_Services('UpdateDailyPerformanceData', ReportDate, RepJSON)
            end
        Case Otherwise$
            Error_Services('Add', 'Unsupported report')
    End Case

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


API reports.HEAD
API reports.GET

    HTTP_Resource_Services('LoremIpsum')

end api
