Compile function OI_Wizard_Services(@Service, @Params)
#pragma precomp SRP_PreCompiler
$Insert LOGICAL
$Insert OI_WIZARD_EQUATES
$Insert OI_WIZARD_TRANSACTIONS_EQUATES
$Insert REACT_MODE_NG_EQUATES
$Insert TIME_INSERTS

Declare function   RTI_CreateGUID, Database_Services, Error_Services, SRP_Json, MemberOf
Declare function   OI_Wizard_Services, Reactor_Services, Reactor_Modes_Services, Datetime
Declare subroutine Database_Services, Error_Services, SRP_Json, Service_Services

GoToService

Return Response or ""

//-----------------------------------------------------------------------------
// SERVICES
//-----------------------------------------------------------------------------

Service CreateWizardID(LSLUserID)
    
    WizardID = RTI_CreateGUID()
    If WizardID NE '' then
        WizardRow                          = ''
        WizardRow<OI_WIZARD.CREATED_DATE$> = Date()
        WizardRow<OI_WIZARD.CREATED_TIME$> = Time()
        WizardRow<OI_WIZARD.TRANS_TYPE$>   = 'Login'
        WizardRow<OI_WIZARD.TERMINATED$>   = False$
        WizardRow<OI_WIZARD.EMPLOYEE_ID$>  = LSLUserID
        Database_Services('WriteDataRow', 'OI_WIZARD', WizardID, WizardRow, True$, False$, True$)
    end else
        Error_Services('Add', 'WizardID was not created in the ' : Service : ' service.')
    end

    Response    = WizardID
    
End Service


//----------------------------------------------------------------------------------------------------------------------
// ConvertMVWizardToJSON
//
// Converts a MultiValue formatted OI_WIZARD row into a serialized JSON object and returns the result. If the mvWizard
// argument is empty, the service will attempt to get it from the OI_WIZARD table. If the itemURL argument is not empty,
// HAL+JSON properties will be added to the JSON object.
//----------------------------------------------------------------------------------------------------------------------
Service ConvertMVWizardToJSON(WizardID, mvWizard, itemURL)

    jsonWizard    = ''

    If WizardID NE '' then

        If mvWizard EQ '' then mvWizard = Database_Services('ReadDataRow', 'OI_WIZARD', WizardID)
        If Error_Services('NoError') then
            @DICT   = Database_Services('GetTableHandle', 'DICT.OI_WIZARD')
            @ID     = WizardID
            @RECORD = mvWizard

            If SRP_JSON(objJSONWizard, 'New', 'Object') then
                // Wizard object.
                If SRP_JSON(objWizard, 'New', 'Object') then
                    SRP_JSON(objWizard, 'SetValue', 'ID', @ID, 'String')
                    If SRP_JSON(objTransArray, 'New', 'Array') then
                        AvailTrans = OI_Wizard_Services('GetAvailTrans', {EMPLOYEE_ID})
                        For each TransType in AvailTrans using @VM setting vPos
                            If SRP_JSON(objTrans, 'New', 'Object') then
                                SRP_JSON(objTrans, 'SetValue', 'ID', TransType, 'String')
                                TransTitle = Xlate('OI_WIZARD_TRANS_TYPES', TransType, 'TITLE', 'X')
                                SRP_JSON(objTrans, 'SetValue', 'Title', TransTitle, 'String')
                                SRP_JSON(objTransArray, 'Add', objTrans)
                                SRP_JSON(objTrans, 'Release')
                            end
                        Next TransType
                        SRP_JSON(objWizard, 'Set', 'availableTransactions', objTransArray)
                        SRP_JSON(objTransArray, 'Release', objTransArray)
                    end
                    SRP_JSON(objJSONWizard, 'Set', 'session', objWizard)
                    SRP_JSON(objWizard, 'Release')
                end
                
                If itemURL NE '' then
                    // The itemURL was passed in so add HAL+JSON properties.

                    // Create the _links property and then all link objects needed for this resource.
                    If SRP_JSON(objLinks, 'New', 'Object') then
                        // Create a self link.
                        If SRP_JSON(objLink, 'New', 'Object') then
                            SRP_JSON(objLink, 'SetValue', 'href', ItemURL, 'String')
                            SRP_JSON(objLink, 'SetValue', 'title', 'Self', 'String')
                            SRP_JSON(objLinks, 'Set', 'self', objLink)
                            SRP_JSON(objLink, 'Release')
                        end
                        SRP_JSON(objJSONWizard, 'Set', '_links', objLinks)
                        SRP_JSON(objLinks, 'Release')
                    end

                    // Create the _form property to help UIs determine what to display.
                    If SRP_JSON(objForm, 'New', 'Object') then
                        If SRP_JSON(arrayFields, 'New', 'Array') then
                            If {EMPLOYEE_ID} NE '' then
                                If SRP_JSON(objField, 'New', 'Object') then
                                    SRP_JSON(objField, 'SetValue', 'label', 'Employee', 'String')
                                    SRP_JSON(objField, 'SetValue', 'value', {EMPLOYEE_NAME}, 'String')
                                    SRP_JSON(arrayFields, 'Add', objField)
                                    SRP_JSON(objField, 'Release')
                                end
                            end
                            SRP_JSON(objForm, 'Set', 'fields', arrayFields)
                            SRP_JSON(arrayFields, 'Release')
                        end
                        SRP_JSON(objJSONWizard, 'Set', '_form', objForm)
                        SRP_JSON(objForm, 'Release')
                    end
                    // Create the _class property for this resource.
                    SRP_JSON(objJSONWizard, 'SetValue', '_class', 'resource')
                end
                jsonWizard    = SRP_JSON(objJSONWizard, 'Stringify', 'Styled')
                SRP_JSON(objJSONWizard, 'Release')
            end else
                Error_Services('Add', 'Unable to create JSON representation in the ' : Service : ' service.')
            end
        end
    end else
        Error_Services('Add', 'WizardID argument was missing in the ' : Service : ' service.')
    end

    Response    = jsonWizard

end service


Service CreateTransaction(OIWizardID, TransType, Data)
    
    If ( (OIWizardID NE '') and (TransType NE '') ) then
        // Create a new OI_WIZARD_TRANSACTIONS record and associate it with the OI Wizard ID.
        Rec                                       = ''
        KeyID                                     = RTI_CreateGUID()
        Rec<OI_WIZARD_TRANSACTIONS.OI_WIZARD_ID$> = OIWizardID
        Rec<OI_WIZARD_TRANSACTIONS.CREATE_DATE$>  = Date()
        Rec<OI_WIZARD_TRANSACTIONS.CREATE_TIME$>  = Time()
        Rec<OI_WIZARD_TRANSACTIONS.COMPLETED$>    = False$
        Rec<OI_WIZARD_TRANSACTIONS.TRANS_TYPE$>   = TransType
        Rec<OI_WIZARD_TRANSACTIONS.DATA$>         = Data
        Database_Services('WriteDataRow', 'OI_WIZARD_TRANSACTIONS', KeyID, Rec)
        If Error_Services('NoError') then
            Response = KeyID
        end else
            Response = False$
        end
    end else
        ErrorMsg = 'Error in ':Service:' service. Null OIWizardID or TransType passed in.'
        Error_Services('Add', ErrorMsg)
        Response = False$
    end
    
end service


Service GetAvailTrans(UserID)
    
    AvailTrans = ''
    If UserID NE '' then
        Open 'OI_WIZARD_TRANS_TYPES' to hTable then
            Select hTable
            EOF = False$
            Loop
                Readnext TransType else EOF = True$
            Until EOF
                PermittedGroups = Xlate('OI_WIZARD_TRANS_TYPES', TransType, 'PERMITTED_GROUPS', 'X')
                Done            = False$
                For each Group in PermittedGroups using @VM setting vPos
                    If MemberOf(UserID, Group) then
                        AvailTrans<0, -1> = TransType
                        Done              = True$
                    end
                Until Done 
                Next Group
            Repeat
            Response = AvailTrans
        end
    end
    
end service


Service ValidateSession(OIWizardID)
    ErrorMsg = ''
    If OIWizardID NE '' then
        OIWizardRec = Database_Services('ReadDataRow', 'OI_WIZARD', OIWizardID, True$, 0, False$)
        If Error_Services('NoError') then
            SessionTerminated = OIWizardRec<OI_WIZARD.TERMINATED$>
            if Not(SessionTerminated) then
                LastDate = OIWizardRec<OI_WIZARD.UPDATED_DATES$>[-1, 'B' : @VM]
                LastTime = OIWizardRec<OI_WIZARD.UPDATED_TIMES$>[-1, 'B' : @VM]
                If LastDate EQ '' then
                    // No updates have occured so use the Create Date/Time.
                    LastDate    = OIWizardRec<OI_WIZARD.CREATED_DATE$>
                    LastTime    = OIWizardRec<OI_WIZARD.CREATED_TIME$>
                end
                lastDateTime = Iconv(Oconv(LastDate, 'D4/') : ' ' : Oconv(LastTime, 'MTS'), 'DTS')
                SessionAge   = (Datetime() - lastDateTime) * SECONDS_IN_DAY$
                MaxAge       = HOUR_IN_SECONDS$ * 12
                If SessionAge LT MaxAge then
                    OIWizardRec<OI_WIZARD.UPDATED_DATES$, -1> = Date()
                    OIWizardRec<OI_WIZARD.UPDATED_TIMES$, -1> = Time()
                    Database_Services('WriteDataRow', 'OI_WIZARD', OIWizardID, OIWizardRec)
                    If Error_Services('HasError') then ErrorMsg = Error_Services('GetMessage')
                end else
                    ErrorMsg                                  = 'Session has expired'
                end
            end else
                ErrorMsg = 'Session has been previously terminated.'
            end
        end else
            ErrorMsg = Error_Services('GetMessage')
        end
    end else
        ErrorMsg = 'Error in ':Service:' service. Null OIWizardID passed in.'
    end
    
    If ErrorMsg EQ '' then
        Response = True$
    end else
        Error_Services('Add', ErrorMsg)
        Response = False$
    end
end service
/*
This routine validates a users session without extending it. Used for OI Wizard sessions that are awaiting input.
*/
Service ValidateSessionIdle(OIWizardID)
    ErrorMsg = ''
    If OIWizardID NE '' then
        OIWizardRec = Database_Services('ReadDataRow', 'OI_WIZARD', OIWizardID, True$, 0, False$)
        If Error_Services('NoError') then
            SessionTerminated = OIWizardRec<OI_WIZARD.TERMINATED$>
            if Not(SessionTerminated) then
                LastDate = OIWizardRec<OI_WIZARD.UPDATED_DATES$>[-1, 'B' : @VM]
                LastTime = OIWizardRec<OI_WIZARD.UPDATED_TIMES$>[-1, 'B' : @VM]
                If LastDate EQ '' then
                    // No updates have occured so use the Create Date/Time.
                    LastDate    = OIWizardRec<OI_WIZARD.CREATED_DATE$>
                    LastTime    = OIWizardRec<OI_WIZARD.CREATED_TIME$>
                end
                lastDateTime = Iconv(Oconv(LastDate, 'D4/') : ' ' : Oconv(LastTime, 'MTS'), 'DTS')
                SessionAge   = (Datetime() - lastDateTime) * 86400
                // 600 seconds = 10 minutes
                If SessionAge GE 600 then
                    ErrorMsg = 'Session has expired'
                end else
                    
                end
            end else
                ErrorMsg = 'Session has been previously terminated.'
            end
        end else
            ErrorMsg = Error_Services('GetMessage')
        end
    end else
        ErrorMsg = 'Error in ':Service:' service. Null OIWizardID passed in.'
    end
    
    If ErrorMsg EQ '' then
        Response = True$
    end else
        Error_Services('Add', ErrorMsg)
        Response = False$
    end
end service


Service TerminateSession(OIWizardID)
    
    ErrorMsg = ''
    If OIWizardID NE '' then
        OIWizardRec = Database_Services('ReadDataRow', 'OI_WIZARD', OIWizardID)
        If Error_Services('NoError') then
            OIWizardRec<OI_WIZARD.TERMINATED$> = True$
            Database_Services('WriteDataRow', 'OI_WIZARD', OIWizardID, OIWizardRec)
            If Error_Services('HasError') then ErrorMsg = Error_Services('GetMessage')
        end
    end else
        ErrorMsg = 'Error in ':Service:' service. Null OIWizardID passed in.'
    end
    
    If ErrorMsg EQ '' then
        Response = True$
    end else
        Error_Services('Add', ErrorMsg)
        Response = False$
    end
    
    
end service


Service UpdateTransaction(TransactionID, FieldData)
    
    ErrorMsg = ''
    If ( (TransactionID NE '') and (FieldData NE '') ) then
        TransactionRec = Database_Services('ReadDataRow', 'OI_WIZARD_TRANSACTIONS', TransactionID)
        If Error_Services('NoError') then
            TransType     = TransactionRec<OI_WIZARD_TRANSACTIONS.TRANS_TYPE$>
            ServiceModule = Xlate('OI_WIZARD_TRANS_TYPES', TransType, 'SERVICE_MODULE', 'X')
            UpdateService = Xlate('OI_WIZARD_TRANS_TYPES', TransType, 'UPDATE_SERVICE', 'X')
            If ( (ServiceModule NE '') and (UpdateService NE '') ) then
                Service_Services('RunService', ServiceModule, UpdateService, FieldData)
                If Error_Services('HasError') then ErrorMsg = Error_Services('GetMessage')
            end
        end else
            ErrorMsg = Error_Services('GetMessage')
        end
    end else
        ErrorMsg = 'Null TransactionID or FieldData passed into service.'
    end
    
    If ErrorMsg EQ '' then
        Response = True$
    end else
        Response = False$
        Error_Services('Add', 'Error in ':Service:' service. ':ErrorMsg)
    end
    
end service


Service CompleteTransaction(TransactionID)
    
    ErrorMsg = ''
    If TransactionID NE '' then
        TransactionRec = Database_Services('ReadDataRow', 'OI_WIZARD_TRANSACTIONS', TransactionID)
        If Error_Services('NoError') then
            TransactionRec<OI_WIZARD_TRANSACTIONS.COMPLETED$> = True$
            Database_Services('WriteDataRow', 'OI_WIZARD_TRANSACTIONS', TransactionID, TransactionRec)
            If Error_Services('HasError') then ErrorMsg = Error_Services('GetMessage')
        end else
            ErrorMsg = Error_Services('GetMessage')
        end
    end else
        ErrorMsg = 'Null TransactionID or FieldData passed into service.'
    end
    
    If ErrorMsg EQ '' then
        Response = True$
    end else
        Response = False$
        Error_Services('Add', 'Error in ':Service:' service. ':ErrorMsg)
    end
    
end service


//----------------------------------------------------------------------------------------------------------------------
// ConvertMVTransactionToJSON
//
// Converts a MultiValue formatted TRANSACTIONS row into a serialized JSON object and returns the result. If the 
// mvTransaction argument is empty, the service will attempt to get it from the TRANSACTIONS table. If the itemURL 
// argument is not empty, HAL+JSON properties will be added to the JSON object.
//----------------------------------------------------------------------------------------------------------------------
Service ConvertMVTransactionToJSON(TransactionID, mvTransaction, itemURL)

    jsonTransaction    = ''

    If TransactionID NE '' then

        If mvTransaction EQ '' then mvTransaction = Database_Services('ReadDataRow', 'OI_WIZARD_TRANSACTIONS', TransactionID)
        If Error_Services('NoError') then
            @DICT    = Database_Services('GetTableHandle', 'DICT.OI_WIZARD_TRANSACTIONS')
            @ID      = TransactionID
            @RECORD  = mvTransaction
            CurrUser = Xlate('OI_WIZARD', {OI_WIZARD_ID}, 'EMPLOYEE_ID', 'X')
            If SRP_JSON(objJSONTransaction, 'New', 'Object') then
                
                // Wizard/Session object
                If SRP_JSON(objWizard, 'New', 'Object') then
                    SRP_JSON(objWizard, 'SetValue', 'ID', {OI_WIZARD_ID}, 'String')
                    SRP_JSON(objJSONTransaction, 'Set', 'session', objWizard)
                    SRP_JSON(objWizard, 'Release')
                end
                
                // Transaction object
                If SRP_JSON(objTransaction, 'New', 'Object') then
                    SRP_JSON(objTransaction, 'SetValue', 'ID', @ID, 'String')
                    SRP_JSON(objTransaction, 'SetValue', 'completed', {COMPLETED}, 'Boolean')
                    // Add transaction required fields
                    SRP_JSON(objTransaction, 'SetValue', 'transType', {TRANS_TYPE}, 'String')
                    TransTitle = Xlate('OI_WIZARD_TRANS_TYPES', {TRANS_TYPE}, 'TITLE', 'X')
                    SRP_JSON(objTransaction, 'SetValue', 'title', TransTitle, 'String')
                    ReqFields  = Xlate('OI_WIZARD_TRANS_TYPES', {TRANS_TYPE}, 'REQUIRED_FIELDS', 'X')
                    SRP_JSON(objTransaction, 'SetValueArray', 'requiredFields', ReqFields, @VM)
                    
                    If {DATA} then
                        Begin Case
                            Case {TRANS_TYPE} EQ 'REACT_MODE_CHG'
                                ReactorNo = {DATA}<0, 1>
                                If ReactorNo then
                                    // Add in reactor current mode, available modes, and available sub categories.
                                    CurrModeKey        = Reactor_Services('GetReactCurrModeId', ReactorNo)
                                    CurrMode           = Xlate('REACT_MODE_NG', CurrModeKey, REACT_MODE_NG_MODE$, 'X')
                                    ServiceDesc        = Xlate('REACT_MODE_NG', CurrModeKey, REACT_MODE_NG_SERVICE_DESC$, 'X')
                                    AvailModes         = Reactor_Modes_Services('AvailableModes', CurrMode, CurrUser)
                                    CurrRLKey          = Xlate('REACT_MODE_NG', CurrModeKey, REACT_MODE_NG_START_RL_ID$ , 'X')
                                    AvailMaintComments = '':@VM:Xlate('APP_INFO', 'REACT_MODE_CHANGE_MAINT_COMMENT_OPTIONS', 1, 'X')
                                    AvailEngrComments  = '':@VM:Xlate('APP_INFO', 'REACT_MODE_CHANGE_ENGR_COMMENT_OPTIONS', 1, 'X')
                                    // Create reactor object
                                    If SRP_JSON(objReactor, 'New', 'Object') then
                                        SRP_JSON(objReactor, 'SetValue', 'reactorNo', ReactorNo, 'String')
                                        SRP_JSON(objReactor, 'SetValue', 'currMode', CurrMode, 'String')
                                        SRP_JSON(objReactor, 'SetValue', 'currModeKey', CurrModeKey, 'String')
                                        SRP_JSON(objReactor, 'SetValue', 'serviceDesc', ServiceDesc, 'String')
                                        SRP_JSON(objReactor, 'SetValue', 'reactLogKey', CurrRLKey, 'Number')
                                        If SRP_JSON(objModesArray, 'New', 'Array') then
                                            For each AvailMode in AvailModes using @FM setting fPos
                                                If SRP_JSON(objMode, 'New', 'Object') then
                                                    SRP_JSON(objMode, 'SetValue', 'mode', AvailMode, 'String')
                                                    SubCats = '':@VM:Xlate('REACTOR_MODES', AvailMode, 'SERVICE_CATEGORIES', 'X')
                                                    SRP_JSON(objMode, 'SetValueArray', 'subCategories', SubCats, @VM)
                                                    SRP_JSON(objModesArray, 'Add', objMode)
                                                    SRP_JSON(objMode, 'Release')
                                                end
                                            Next AvailMode
                                            // Add modes array object to reactor object
                                            SRP_JSON(objReactor, 'Set', 'availableModes', objModesArray)
                                            SRP_JSON(objModesArray, 'Release')
                                        end
                                        If SRP_JSON(objComments, 'New', 'Array') then
                                        	If SRP_JSON(maintComments, 'New', 'Object') then
                                        		SRP_Json(maintComments, 'SetValue', 'category', 'WAITING_FOR_MAINTENANCE_UNSCHEDULED', 'String')
                                        		SRP_Json(maintComments, 'SetValueArray', 'comments', AvailMaintComments, @VM)
                                        		SRP_Json(objComments, 'Add', maintComments)
                                        		SRP_Json(maintComments, 'Release')
                                        	end
                                        	If SRP_JSON(engrComments, 'New', 'Object') then
                                        		SRP_Json(engrComments, 'SetValue', 'category', 'WAITING_FOR_ENGTECH_UNSCHEDULED', 'String')
                                        		SRP_Json(engrComments, 'SetValueArray', 'comments', AvailEngrComments, @VM)
                                        		SRP_Json(objComments, 'Add', engrComments)
                                        		SRP_Json(engrComments, 'Release')
                                        	end
                                        	SRP_JSON(objReactor, 'Set', 'availableComments', objComments)
                                        	SRP_JSON(objComments, 'Release')
                                        end
                                        SRP_JSON(objTransaction, 'Set', 'reactor', objReactor)
                                        SRP_JSON(objReactor, 'Release')
                                    end
                                end
                        End Case
                    end
                    
                    SRP_JSON(objJSONTransaction, 'Set', 'transaction', objTransaction)
                    SRP_JSON(objTransaction, 'Release')
                end
                
                If itemURL NE '' then
                    // The itemURL was passed in so add HAL+JSON properties.

                    // Create the _links property and then all link objects needed for this resource.
                    If SRP_JSON(objLinks, 'New', 'Object') then
                        // Create a self link.
                        If SRP_JSON(objLink, 'New', 'Object') then
                            SRP_JSON(objLink, 'SetValue', 'href', ItemURL, 'String')
                            SRP_JSON(objLink, 'SetValue', 'title', 'Self', 'String')
                            SRP_JSON(objLinks, 'Set', 'self', objLink)
                            SRP_JSON(objLink, 'Release')
                        end
                        SRP_JSON(objJSONTransaction, 'Set', '_links', objLinks)
                        SRP_JSON(objLinks, 'Release')
                    end

                    // Create the _form property to help UIs determine what to display.
                    If SRP_JSON(objForm, 'New', 'Object') then
                        If SRP_JSON(arrayFields, 'New', 'Array') then
                            If SRP_JSON(objField, 'New', 'Object') then
                                SRP_JSON(objField, 'SetValue', 'label', 'Example Label', 'String')
                                SRP_JSON(objField, 'SetValue', 'value', 'Example Value', 'String')
                                SRP_JSON(arrayFields, 'Add', objField)
                                SRP_JSON(objField, 'Release')
                            end
                            SRP_JSON(objForm, 'Set', 'fields', arrayFields)
                            SRP_JSON(arrayFields, 'Release')
                        end
                        SRP_JSON(objJSONTransaction, 'Set', '_form', objForm)
                        SRP_JSON(objForm, 'Release')
                    end
                    // Create the _class property for this resource.
                    SRP_JSON(objJSONTransaction, 'SetValue', '_class', 'resource')
                end
                jsonTransaction    = SRP_JSON(objJSONTransaction, 'Stringify', 'Styled')
                SRP_JSON(objJSONTransaction, 'Release')
            end else
                Error_Services('Add', 'Unable to create JSON representation in the ' : Service : ' service.')
            end
        end
    end else
        Error_Services('Add', 'TransactionID argument was missing in the ' : Service : ' service.')
    end

    Response    = jsonTransaction

end service

