Option Explicit

Private Const cenDat = 32
Private Const adCmdText = 1
Private Const cenDSEnsureOpenConnection = 1

Private m_strLastSID
Private m_strLastSIDLic1
Private m_strLastSIDLic2
Private m_strLastSIDLic3

Private m_blnLic1Set
Private m_blnLic2Set
Private m_blnLic3Set

Public Function GetMappedFieldValue(ByVal objMappedFieldInfo, _
                                    ByVal varRSValue, _
                                    ByVal objCenApp)
On Error Resume Next
    
    Const FIELD_NAME_END_DATE = "End_date"
    Const FIELD_END_DATE_FIND_VALUE = "12/31/2999"
    Const FIELD_END_DATE_REPLACE_VALUE = ""
    Const FIELD_NAME_AD_ENABLED = "AD_User_Status_Disabled"
    Const VAL_ENABLED = "0"
    Const VAL_DISABLED = "1"
    
    Dim varMappedValue
    Dim varPrevValue
	
    varMappedValue = Null
 	
    If objMappedFieldInfo.InternalFieldName = FIELD_NAME_END_DATE Then
        varMappedValue = varRSValue

        If varMappedValue = FIELD_END_DATE_FIND_VALUE Then
            varMappedValue = FIELD_END_DATE_REPLACE_VALUE
        End If

        GetMappedFieldValue = varMappedValue
        Exit Function
    ElseIf objMappedFieldInfo.InternalFieldName = FIELD_NAME_AD_ENABLED Then
        If varRSValue <> Empty Then
           if (varRSValue And 2) <> 0 Then
              varMappedValue = VAL_DISABLED
           Else
              varMappedValue = VAL_ENABLED
           End If
	Else
	    varMappedValue = VAL_ENABLED
        End If

        GetMappedFieldValue = varMappedValue
        Exit Function
    End If

    If objMappedFieldInfo.ValueTableID > 0 Then
        varMappedValue = ConvertSingleChoiceVal(varRSValue, objCenApp, objMappedFieldInfo)
    Else
        'If objMappedFieldInfo.ExternalFieldName = "CUSTNMBR" And objMappedFieldInfo.InternalFieldName = "great_plains_id" Then
        '        varMappedValue = RemovePrefix(varRSValue, "C0")
        'Else
                varMappedValue = varRSValue
        'End If
    End If
    
	'LogMsg "Set " & objMappedFieldInfo.InternalFieldName & "=" & varMappedValue
    GetMappedFieldValue = varMappedValue
    
End Function


Private Sub LogMsg(strMsg)
    Dim moEventLogger

	'If DEBUG_ON Then
        'This "IF" is in case we make the variable private to the module and we do not create it and destroy it every call
        'If moEventLogger is Nothing then
            Set moEventLogger = CreateObject("MqSysutils40.CMqEventLogger")
        
            moEventLogger.InitializeEventLogger
        'End If

        If Not IsNull(strMsg) Then
                moEventLogger.LogEvent CStr(strMsg)
        End If
	'End If
End Sub


Private Function ConvertSingleChoiceVal(ByVal varRSValue, _
                                            ByVal objCenApp, _
                                            ByVal objMappedFieldInfo)
On Error Resume Next
    
    Dim objChoiceVal
    Dim lngCount
    Dim varKeys
    Dim lngChoiceVal
    Dim lngDSType
    Dim strTableName
    Dim strSQL
    Dim rsValTable
    Dim rsChoiceList
    
    Const cenDSEnsureOpenConnection = 1
    Const cenUsers = 16
    
    Const FLD_SRC_TBL_NAME = "tSourceTableName"
    Const FLD_DS_TYPE = "nDSType"
    Const FLD_ID = "nID"
    Const TBL_DTS_FLD_VAL_TBLS = "tblDtsFieldValueTables"
    
    If Not IsNull(varRSValue) Then
        
        lngChoiceVal = varRSValue
        
        If IsNumeric(varRSValue) Then
            'assume if it's a number then it's a choice list value
            lngChoiceVal = CLng(varRSValue)
        Else
            If Len(CStr(varRSValue)) > 0 Then
                strSQL = "SELECT [" & FLD_SRC_TBL_NAME & "], [" & FLD_DS_TYPE & "] FROM [" & _
                                TBL_DTS_FLD_VAL_TBLS & "] WHERE [" & FLD_ID & "]=" & _
                                        objMappedFieldInfo.ValueTableID
                
                Set rsValTable = objCenApp.DataStores(cenUsers).GetConnection(cenDSEnsureOpenConnection).Execute(strSQL)
                
                If Not rsValTable.EOF Then
                    strTableName = rsValTable.Fields(FLD_SRC_TBL_NAME).Value
                    lngDSType = CLng(rsValTable.Fields(FLD_DS_TYPE).Value)
                
                    'get the ID
                        If objMappedFieldInfo.ExternalFieldName = "CUSTNMBR" And objMappedFieldInfo.InternalFieldName = "nCompanyName" Then
                                strSQL = "SELECT [nID] FROM [" & strTableName & "] WHERE [great_plains_id]='" & _
                                        EscQuote(varRSValue) & "'"
                        Else
                                strSQL = "SELECT [nID] FROM [" & strTableName & "] WHERE [tName]='" & _
                                        EscQuote(varRSValue) & "'"
                        End If

                    Set rsChoiceList = objCenApp.DataStores.Item(CLng(lngDSType)).GetConnection(cenDSEnsureOpenConnection).Execute(strSQL)
                    
                    If Not rsChoiceList.EOF Then
                        lngChoiceVal = rsChoiceList.Fields("nID").Value
                    End If
                    
                    If Not rsChoiceList Is Nothing Then
                        rsChoiceList.Close
                        Set rsChoiceList = Nothing
                    End If
                    
                End If
                
                If Not rsValTable Is Nothing Then
                    rsValTable.Close
                    Set rsValTable = Nothing
                End If
            End If
        End If
    End If

    ConvertSingleChoiceVal = lngChoiceVal

End Function

Private Function RemovePrefix(ByVal varRSValue, ByVal strPrefix)
On Error Resume Next
    
    Dim strValue
    Dim lngLen

    If Not IsNull(varRSValue) Then
    
        strValue = varRSValue
        lngLen = Len(strValue)

        strValue = MqStrMan_StripLeading(strValue, strPrefix)

        If Len(strValue) < lngLen Then
            'we removed something
            'remove any 0s
            lngLen = 0
            Do While lngLen <> Len(strValue)
                lngLen = Len(strValue)
                strValue = MqStrMan_StripLeading(strValue, "0")
            Loop
        End If
    Else
        strValue = ""
    End If

    RemovePrefix = strValue
End Function

Private Function MqStrMan_StripLeading(ByVal strString, ByVal strRemoveString)
    On Error Resume Next
    Dim lngLength
    Dim strTempString
    strTempString = Trim(strString)
    If Len(strTempString) > 0 Then
        lngLength = Len(strRemoveString)
        If StrComp(strRemoveString, Left(strTempString, lngLength), vbTextCompare) = 0 Then
            strTempString = Right(strTempString, Len(strTempString) - lngLength)
        End If
    End If
    MqStrMan_StripLeading = strTempString
    
End Function

Public Function GetUniqueIDForKeys(ByVal objMappedFieldInfo, _
ByVal varRSValue, _
ByVal objCenApp, _
ByVal rsConnDB)

	'On Error Resume Next
    	Dim sRet
	Dim strSQL
	Dim rsRecord
	CONST FLD_KEY_APP_NAME = "Key_Discovery___Application_Name"

	GetUniqueIDForKeys = varRSValue
	
	' Check first if the name matches directly the name of the app in the Installations Catalog
	strSQL = "SELECT I.[tSID] FROM [InventoriedSoftware01_Dat].[dbo].[tblDts] as IC " & _ 
				"INNER JOIN [Installations01_Dat].[dbo].[tblDts] as I " & _
					"ON IC.tSID=I.tAppSID " & _
				"WHERE IC.[Application_Name]='" & EscQuote(rsConnDB.Fields("Application_Name").Value) & "'" & _
					" AND I.[Device_Name]='" & EscQuote(rsConnDB.Fields("Device_Name").Value) & "'"

	Set rsRecord = objCenApp.CurrentProject.DataStores(cenDat).GetConnection(cenDSEnsureOpenConnection).Execute(strSQL, , adCmdText)

	If Not rsRecord.EOF Then
		sRet = IfNull(rsRecord.Fields("tSID").Value)
	Else
		
	
	
		' Otherwise, check if the name matches the application name for the Keys in the Installations Catalog
		strSQL = "SELECT I.[tSID] FROM [InventoriedSoftware01_Dat].[dbo].[tblDts] as IC " & _ 
					"INNER JOIN [Installations01_Dat].[dbo].[tblDts] as I " & _
						"ON IC.tSID=I.tAppSID " & _
					"WHERE IC.[" & FLD_KEY_APP_NAME & "]='" & EscQuote(rsConnDB.Fields("Application_Name").Value) & "'" & _
						" AND I.[Device_Name]='" & EscQuote(rsConnDB.Fields("Device_Name").Value) & "'"

		Set rsRecord = objCenApp.CurrentProject.DataStores(cenDat).GetConnection(cenDSEnsureOpenConnection).Execute(strSQL, , adCmdText)

		If Not rsRecord.EOF Then
			sRet = IfNull(rsRecord.Fields("tSID").Value)
		Else
		
			' Return the same value
			sRet = varRSValue
		End If

	End If
	
	GetUniqueIDForKeys = sRet
		
End Function

Private Function IfNull(varField)
On Error Resume Next
    If IsNull(varField) Or IsEmpty(varField) Then
        IfNull = ""
    Else
        IfNull = CStr(varField)
    End If

End Function

Public Function EscQuote(ByVal strString)
    EscQuote = Replace(CStr(strString), "'", "''")
End Function

Public Function GetLicenseKey(ByVal objMappedFieldInfo, _
ByVal varRSValue, _
ByVal objCenApp, _
ByVal rsConnDB)

	Dim strSID
	Dim strLicKey
	
	strLicKey = ""
	
	strSID = GetUniqueIDForKeys(objMappedFieldInfo, varRSValue, objCenApp, rsConnDB)
	
	If strSID <> varRSValue Then
		If m_strLastSID <> strSID Then
			m_blnLic1Set = False
			m_blnLic2Set = False
			m_blnLic3Set = False
			'LogMsg "In GetLicenseKey for " & objMappedFieldInfo.InternalFieldName & "; strSID=" & strSID & "; varRSValue=" & varRSValue
			strLicKey = varRSValue
			m_strLastSID = strSID
			m_strLastSIDLic1 = strLicKey
			m_blnLic1Set = True
		Else
			If varRSValue <> m_strLastSIDLic1 Then
				If objMappedFieldInfo.InternalFieldName = "License_Key_2" Then
					If m_blnLic2Set = False Then
						'LogMsg "Same SID, field 2 " & varRSValue
						strLicKey = varRSValue
						m_strLastSIDLic2 = strLicKey
						m_blnLic2Set = True
					End If
					
				ElseIf objMappedFieldInfo.InternalFieldName = "License_Key_3" Then
					If varRSValue <> m_strLastSIDLic2 Then
						If m_blnLic3Set = False Then
							'LogMsg "Same SID, field 3 " & varRSValue
							strLicKey = varRSValue
							m_strLastSIDLic3 = strLicKey
							m_blnLic3Set = True
						End If
					End If
				End If
			End If
		End If
	End If
	
	GetLicenseKey = strLicKey
End Function
