' Simple container object holding document fields and tables
' added in CC-001115
Class DMSDocument
    Public Fields
    Public Tables
End Class

'**********************************************************
' Class ControlledPrinting
' @description: Provides access to function for controlled printing
'**********************************************************
Class ControlledPrinting
    
  
	'**********************************************************
	' Function: initControlledWithdraw
	' @description:
	'   Checks whether exactly one document is present in the workflow file.
	'   If no document is found, an error message is set and the workflow
	'   is marked as incorrect.
	'
	' @parameters: None
	' @return: No explicit return value (used for workflow control only)
	' added in CC-001115
	'**********************************************************
	Function initControlledWithdraw
		if thisprocess.WFFile.FileObjects.Count = 0 then 'no object in the wffile
			wfvariables.sError.Value = "StandardWF;;;OnlyOneDocument;;;Sie müssen genau eine Dokument an diesen Workflow übergeben."
			wfvariables.bCorrect.Value = 1
			Exit Function
		end If
	End Function
	
	
    
    '**********************************************************
    ' updateWithdrawPrintTable
    ' @description: Updates the print table of the current document. Loads the XML document structure and reads the table "rManagedCopies".
    ' @return: Nothing
	' added in CC-001115
    '**********************************************************	
    Function updateWithdrawPrintTable ()		
		debug2File "[FUNC] updateWithdrawPrintTable START"

		Dim xmlFile
		xmlFile = getObjectDetails( _
			wfvariables.recStructure.iDocumentID.value, _
			wfvariables.recStructure.iDocumentType.Value, _
			"" _
		)

		debug2File "[INFO] XML path: " & xmlFile

		Dim doc
		Set doc = convertXMLtoDMSDocument(xmlFile)

		If doc Is Nothing Then
			debug2File "[ERROR] convertXMLtoDMSDocument returned Nothing"
			Exit Function
		End If

		' --- check if required table exists ---
		If Not doc.Tables.Exists("rManagedCopies") Then
			debug2File "[ERROR] Table rManagedCopies not found in document"
			Exit Function
		End If

		Dim copies
		copies = doc.Tables("rManagedCopies")

		If Not IsArray(copies) Then
			debug2File "[ERROR] rManagedCopies is not an array"
			Exit Function
		End If

		Dim upper
		On Error Resume Next
		upper = UBound(copies)
		If Err.Number <> 0 Then
			debug2File "[WARN] rManagedCopies table is empty"
			Err.Clear
			Exit Function
		End If
		On Error GoTo 0

		debug2File "[INFO] rManagedCopies rows: " & (upper + 1)
		
		Dim maxRows
		maxRows = UBound(copies)
		
		For r = 0 To wfvariables.recPrintouts.Count - 1
			If r > maxRows Then
				debug2File "[WARN] Missing XML row for workflow printout row " & r
				Exit For
			End If
			
			Set rowObj = copies(r)
			If rowObj.Exists("sDestroyedBy") Then
				if  Len(wfvariables.recPrintouts.Item(r).Item("sDestroyedBy").Value) > 0  and Len(Trim(rowObj("sDestroyedBy"))) = 0  Then
					rowObj("sDestroyedBy") = wfvariables.recPrintouts.Item(r).Item("sDestroyedBy").Value
					rowObj("sReturned") = wfvariables.recPrintouts.Item(r).Item("sDestroyed").Value
					rowObj("dReturnDate") = wfvariables.recPrintouts.Item(r).Item("dDestroyedOn").Value
				Else
					debug2File "[ROW " & r & "] Vernichtet durch (DMS): " & rowObj("sDestroyedBy")
					debug2File "[ROW " & r & "] Vernichtet durch (WF): " & wfvariables.recPrintouts.Item(r).Item("sDestroyedBy").Value
				End if 
			Else
				debug2File "[ROW " & r & "] column sDestroyedBy not found"
			End If
		next

		updateRManagedTable(copies)

		debug2File "[FUNC] updateWithdrawPrintTable END"
    End Function
		



	'**********************************************************
	' updateRManagedTable
	' @description:
	'   Updates the Printout table of the controlled document.
	'   If sTableFieldsIn is passed, it will be used directly.
	'   Otherwise the rows are generated from wfvariables.recPrintouts.
	'
	' @param bReplaceTableFields
	'   True  = replace table fields
	'   False = add table fields
	'
	' @param sTableFieldsIn
	'   Optional XML row string (<Row>...</Row><Row>...</Row>)
	'
	' @return Nothing
	' added in CC-001115
	'**********************************************************
	Function updateRManagedTable(rows)
		debug2File "start updateRManagedTable"

		Dim RC, PrmIn, PrmOut
		Dim sTableFields, sXML
		Dim dom, iRet

		Set RC = RunningContext
		Set PrmIn = RC.NewJobsParams
		Set PrmOut = RC.NewJobsParams

		sTableFields = buildPrintTableRows(rows)
		sXML = buildDocumentPrintTableXML(sTableFields)

		debug2file sXML

		Set dom = CreateObject("MSXML2.DOMDocument")
		dom.loadXML sXML

		PrmIn.Value("Flags") = 0
		PrmIn.Value("Options") = "CHECKREADONLY=0;REPLACETABLEFIELDS=1"
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId")
		PrmIn.Value("XML") = dom

		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)

		If iRet = 0 Then
			debug2File vbTab & "updateRManagedTable successful..."
		Else
			debug2File vbTab & "ERROR: updateRManagedTable failed..."
		End If

		debug2File "end updateRManagedTable"
	End Function


	'**********************************************************
	' buildPrintTableRows
	' @description:
	'   Creates the <Row>...</Row> XML for rManagedCopies
	' added in CC-001115
	'**********************************************************
	Function buildPrintTableRows(rows)

		Dim sRows, i, ub
		sRows = ""

		If Not IsArray(rows) Then
			buildPrintTableRows = sRows
			Exit Function
		End If

		On Error Resume Next
		ub = UBound(rows)
		If Err.Number <> 0 Then
			Err.Clear
			On Error GoTo 0
			buildPrintTableRows = sRows
			Exit Function
		End If
		On Error GoTo 0

		For i = 0 To UBound(rows)
			If rows(i)("iLocked") <> 1 Then
				sRows = sRows & "<Row>"
				sRows = sRows & buildField("sCreator",     rows(i)("sCreator"),      True, False)
				sRows = sRows & buildField("sResponsible", rows(i)("sResponsible"),  True, False)
				sRows = sRows & buildField("dDate",        rows(i)("dDate"),    False, True)
				sRows = sRows & buildField("dReturnDate",  rows(i)("dReturnDate"),  False, True)
				sRows = sRows & buildField("sReturned",    rows(i)("sReturned"),    True, False)
				sRows = sRows & buildField("sLocation",    rows(i)("sLocation"),     True, False)
				sRows = sRows & buildField("sComment",     rows(i)("sComment"),      True, False)
				sRows = sRows & buildField("sDestroyedBy", rows(i)("sDestroyedBy"), True, False)
				sRows = sRows & "</Row>"
			End If
		Next

		buildPrintTableRows = sRows

	End Function


	'**********************************************************
	' buildField
	' @description:
	'   Creates a single <Field internal_name='...'>...</Field>
	'
	' @param sInternalName
	' @param vValue
	' @param bEscapeXML
	' @param bConvertDate
	' added in CC-001115
	'**********************************************************
	Function buildField(sInternalName, vValue, bEscapeXML, bConvertDate)

		Dim sValue
		sValue = ""

		If IsEmpty(vValue) Or IsNull(vValue) Then
			sValue = ""
		Else
			sValue = CStr(vValue)
		End If

		If bConvertDate Then
			sValue = convertToOSDate(sValue)
		End If

		If bEscapeXML = True Then
			sValue = convertToValidXML(sValue)
		End If

		buildField = "<Field internal_name='" & sInternalName & "'>" & sValue & "</Field>"

	End Function


	'**********************************************************
	' buildDocumentPrintTableXML
	' @description:
	'   Wraps the row XML into the full DMSData XML
	' added in CC-001115
	'**********************************************************
	Function buildDocumentPrintTableXML(sTableFields)

		Dim sXML

		sXML = ""
		sXML = sXML & "<DMSData>"
		sXML = sXML &   "<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>"
		sXML = sXML &     "<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>"
		sXML = sXML &       "<Object object_id='" & wfvariables.recStructure.iDocumentID.Value & "'>"
		sXML = sXML &         "<TableFields>"
		sXML = sXML &           "<TableField internal_name='rManagedCopies'>"
		sXML = sXML &             sTableFields
		sXML = sXML &           "</TableField>"
		sXML = sXML &         "</TableFields>"
		sXML = sXML &       "</Object>"
		sXML = sXML &     "</ObjectType>"
		sXML = sXML &   "</Archive>"
		sXML = sXML & "</DMSData>"

		buildDocumentPrintTableXML = sXML

	End Function

	'**********************************************************
	' Loads a document XML and converts it into a DMSDocument
	' structure containing:
	'
	' doc.Fields("fieldName")
	' doc.Tables("tableName") -> Array of row dictionaries
	' added in CC-001115
	'**********************************************************
	Function convertXMLtoDMSDocument(xmlPath)

		debug2File "[FUNC] convertXMLtoDMSDocument START"

		Dim xml
		Set xml = CreateObject("MSXML2.DOMDocument")
		xml.async = False

		If Not xml.Load(xmlPath) Then
			debug2File "[ERROR] XML load failed: " & xml.parseError.reason
			Exit Function
		End If

		debug2File "[INFO] XML loaded successfully"

		Dim doc
		Set doc = New DMSDocument
		Set doc.Fields = CreateObject("Scripting.Dictionary")
		Set doc.Tables = CreateObject("Scripting.Dictionary")


		' ----------------------------
		' Read simple document fields
		' ----------------------------
		Dim fieldNodes, fieldNode
		Set fieldNodes = xml.selectNodes("//Fields/Field")

		debug2File "[STEP] Reading fields (" & fieldNodes.length & ")"

		For Each fieldNode In fieldNodes

			Dim fieldName
			fieldName = fieldNode.getAttribute("internal_name")

			If fieldName <> "" Then
				doc.Fields(fieldName) = fieldNode.text
			End If

		Next

		' ----------------------------
		' Read table fields
		' ----------------------------
		Dim tableNodes, tableNode
		Set tableNodes = xml.selectNodes("//TableField")

		debug2File "[STEP] Reading tables (" & tableNodes.length & ")"

		For Each tableNode In tableNodes

			Dim tableName
			tableName = tableNode.getAttribute("internal_name")

			debug2File "[TABLE] " & tableName

			Dim tableRows
			Dim rowCount
			tableRows = Array()
			rowCount = -1

			Dim colNodes, rowNodes
			Set colNodes = tableNode.selectNodes("Columns/Column")
			Set rowNodes = tableNode.selectNodes("Row")

			debug2File "[TABLE] columns: " & colNodes.length & " rows: " & rowNodes.length

			Dim rowNode

			For Each rowNode In rowNodes

				Dim rowDict
				Set rowDict = CreateObject("Scripting.Dictionary")

				Dim valueNodes
				Set valueNodes = rowNode.selectNodes("Value")

				Dim i

				For i = 0 To colNodes.length - 1

					Dim colName
					colName = colNodes.item(i).getAttribute("internal_name")

					If colName <> "" Then

						If i < valueNodes.length Then
							rowDict(colName) = valueNodes.item(i).text
						Else
							rowDict(colName) = ""
						End If

					End If

				Next

				rowCount = rowCount + 1
				ReDim Preserve tableRows(rowCount)
				Set tableRows(rowCount) = rowDict

			Next

			debug2File "[TABLE] stored rows: " & (rowCount + 1)

			doc.Tables(tableName) = tableRows

		Next

		Set convertXMLtoDMSDocument = doc

		debug2File "[FUNC] convertXMLtoDMSDocument END"

	End Function

End Class