REM  *****  BASIC  *****
Option Explicit

Type SondageSettings
	oFieldAliasesRange as Variant
End Type

Type SondageContext
	oDoc as Variant
	oSheet as Variant
	oRange as Variant
	headerRow&
	startColumn&
	startRow&
	endColumn&
	endRow&
End Type

Private priceListPath as String

Public Function Env(Value As Variant) As String
    Env = Environ(Value)
End Function

Type Product
	Title as Variant ' com.sun.star.text.XText
	Price as Integer
	Description as String
End Type

'https://ask.libreoffice.org/t/how-to-know-if-the-file-is-open/77760/7
Function ReturnComponentIfOpen(Byval filePath As String) as Object
	Dim oComp
	filePath=ConvertToUrl(filePath)
	For Each oComp In StarDesktop.Components
		If HasUnoInterfaces(oComp, "com.sun.star.frame.XModel") Then  ' component which has URL
			If oComp.Url=filePath Then
				ReturnComponentIfOpen = oComp
				Exit Function
			End If
		End If
	Next oComp
End Function

Function CreateProperty(key as String, val as Variant) as com.sun.star.beans.PropertyValue
	Dim oProp As New com.sun.star.beans.PropertyValue
	oProp.Name = key
	oProp.Value = val
	CreateProperty = oProp
End Function

Function GetHomePath() as Object
	Dim oPathSub
	oPathSub = CreateUnoService("com.sun.star.util.PathSubstitution")
	GetHomePath = oPathSub.getSubstituteVariable("home") & "/"
End Function

Function ReadProductFromSheet(oSheet as Object, sProductName as String) as Product
	' TODO FIX: Return the correct Product details instead of first item
	Dim oProduct as Product
	Dim iPrice
	Dim oTitle
	Dim iChannel as Integer
	Dim oCalcDoc
	Dim oCursor, oCell
	Dim bProductFound: bProductFound = False
	Dim i, j, iRow, iColumn as Integer
	Dim sCalcFile: sCalcFile = ConvertToUrl(priceListPath)
	
	Dim oArgs(0) as new com.sun.star.beans.PropertyValue
	oArgs(0).Name = "Hidden"
	oArgs(0).Value = True

	oCursor = UsedRangeCursor(oSheet)
	iRow = oCursor.getRows().Count()
	iColumn = oCursor.getColumns().getCount()
	
	' TODO Use Column headers for retrieving data
	For i = 1 To iRow - 1
		oCell = oSheet.getCellByPosition(0, i)
		If oCell.String = sProductName Then
			bProductFound = True
			Goto CLOSE_SHEET_AND_REFLECT:
		End If
	Next i
	
CLOSE_SHEET_AND_REFLECT:
	If bProductFound Then
		oTitle = oSheet.getCellByPosition(1, i).getString()
		oProduct.Title = oCursor
		'############################
		oProduct.Price = oSheet.getCellByPosition(3, i).getValue()
	End If
	ReadProductFromSheet = oProduct
	oCalcDoc.close(True)
End Function

Function GetNumberFormatNumber(oLocale as com.sun.star.lang.Locale, ByRef oFormats, formatStr as String) as Integer
	Dim formatNum as Long
	GetNumberFormatNumber = -1
	formatNum = oFormats.queryKey(formatStr, oLocale, False)
	' add formatStr if it doesn't exist
	If formatNum = -1 Then
		formatNum = oFormats.addNew(formatStr, oLocale)
	End If
	GetNumberFormatNumber = formatNum
End Function

Sub FormatRangeAsNumber(oLocale as com.sun.star.lang.Locale, ByRef oFormats, oRange, formatStr as String)
	' BASIC equivalent of 'Text to Columns'
	Dim formatNum as Long, i as Integer
	Dim oReplace
	oReplace = oRange.createReplaceDescriptor()
	
	If oRange.getCellByPosition(0,0).getValue() = 0 Then
		formatNum = GetNumberFormatNumber(oLocale, oFormats, formatStr)
		If formatNum = -1 Then
			ErrolLocal$ = "Cannot add " & formatStr & " as NumberFormat"
			Exit Sub
		End If
		' https://ask.libreoffice.org/t/macro-calc-convert-column-to-date-similar-text-to-columns/92168/20
		With oReplace
			.searchString = ".+"
			.replaceString = "&"
			.SearchRegularExpression = True
		End With

		oRange.NumberFormat = formatNum
		oRange.replaceAll(oReplace)
	End If
End Sub

Function GetColumnRange(ctx as SondageContext, columnName as String, Optional shouldIncludeHeader as Boolean) as Object
	Dim iHeaderPos
	If IsMissing(shouldIncludeHeader) Then shouldIncludeHeader = False
	iHeaderPos = GetHeaderPosition(ctx, columnName)
	If iHeaderPos = -1 Then
		GetColumnRange = ctx.oSheet.getCellRangeByPosition(0, 0, 0, 0)
		Exit Function
	End If
	GetColumnRange = ctx.oSheet.getCellRangeByPosition(iHeaderPos, IIf(shouldIncludeHeader, ctx.headerRow, ctx.startRow), iHeaderPos, ctx.endRow)
End Function

Function RemoveColumns(ctx as SondageContext, columnNames) as Long
	Dim columnName as String
	Dim iHeader as Integer
	RemoveColumns = ctx.endColumn
	For Each columnName in columnNames
		iHeader = GetHeaderPosition(ctx, columnName)
		If iHeader <> -1 Then
			ctx.oSheet.getColumns().removeByIndex(iHeader, 1)
			ctx.endColumn = ctx.endColumn - 1
		End If
	Next
	RemoveColumns = ctx.endColumn
End Function

Function RemoveColumnsExcept(ctx as SondageContext, columnNames as Variant) as Long
	Dim headerStr as String, columnName as String
	Dim i% : i = 0
	Dim rI% : rI = 0
	Dim columnsToRemove(ctx.endColumn) as String
	Dim headerRange, headerData
	Dim found as Boolean : found = False
	RemoveColumnsExcept = ctx.endColumn

	headerRange = ctx.oSheet.getCellRangeByPosition(0, 0, ctx.endColumn, 0)
	headerData = headerRange.getFormulaArray()

	' TODO Handle condition when columnNames does not have valid header
	' This causes an extra string element in the array
	For i = 0 To UBound(headerData(0))
		headerStr = headerData(0)(i)
		found = False
		For Each columnName in columnNames
			If headerStr = columnName Then
				found = True
				Exit For
			End If
		Next columnName
		If Not found Then
			columnsToRemove(rI) = headerStr
			rI = rI + 1
		End If
	Next i
	
	If i = 0 Then
		Exit Function
	End If

	If rI = 0 Then
		RemoveColumnsExcept = ctx.endColumn
		Exit Function
	End If
	ReDim Preserve columnsToRemove(rI - 1)
	
	RemoveColumnsExcept = RemoveColumns(ctx, columnsToRemove)
End Function

Sub ApplyTheme(ByRef oDoc, sFileName As String)
	Dim oFamilies
	Dim aOptions(0) as New com.sun.star.beans.PropertyValue
	Dim stylesDir()
	Dim StylePath as String
	GlobalScope.BasicLibraries.loadLibrary("Tools")
	oFamilies = oDoc.StyleFamilies
	StylesDir = GetOfficeSubPath("Template", "wizard/styles/")
	StylePath = StylesDir & sFileName
	aOptions(0).Name = "OverwriteStyles"
	aOptions(0).Value = true
	oFamilies.loadStylesFromURL(StylePath, aOptions())
End Sub

Function NaiveLastTable(ctx as SondageContext) as Long
	' Return the row position last table that is separated by an empty row
	Dim oRows
	Dim iRow as Long
	Dim usedRange
	NaiveLastTable = 0
	oRows = ctx.oRange.Rows

	For iRow = 0 To oRows.getCount() - 1
		If oRows.getByIndex(iRow).computeFunction(com.sun.star.sheet.GeneralFunction.COUNT) = 0 Then
			NaiveLastTable = iRow
		End If
	Next
End Function

Function IsValidFileName(fileName as String) as Boolean
    Dim invalidChars as String : invalidChars = "\/:*?""<>|"
    Dim c as String
    Dim i as Integer
    IsValidFileName = False
    For i = 1 To Len(fileName)	
   		c = Mid(fileName, i, 1)
    	If InStr(invalidChars, c) > 0 Then
    		Print "Invalid character '" & c & "' found in '" & fileName & "'"
    		Exit Function
    	End If
    Next
    IsValidFileName = True
End Function

Function ExportAs(oDoc, oSheet, exportPrefix$, exportDestDir$, exportExt$) as Boolean
	Dim cursor as Object
	Dim args(2) as New com.sun.star.beans.PropertyValue
	Dim fd(2) as New com.sun.star.beans.PropertyValue
	Dim fileName as String, fileUrl
	ExportAs = False
	On Error GoTo ErrorHandler
	
	If Not IsValidFileName(oSheet.Name) Then
		ErrorLocal$ = "Sheet has invalid characters for file export"
		Exit Function
	End If
	
	'If Right(exportPrefix, 1) = "/" Or Right(exportPrefix, 1) = "\" Then
	'	exportPrefix = Left(exportPrefix, Len(exportPrefix) - 1)

	fileUrl = ConvertToUrl(exportPrefix)
	If Not FileExists(fileUrl) Then
		ErrorLocal$ =  "FATAL: " & fileUrl & " does not exist"
		Exit Function
	End If

	fileUrl = ConvertToUrl(exportPrefix & GetPathSeparator() & exportDestDir)
	If Not FileExists(fileUrl) Then
			Mkdir fileUrl
	End If

	fileName = exportPrefix & GetPathSeparator() & exportDestDir & GetPathSeparator() & oSheet.Name & "." & exportExt
	fileUrl = ConvertToUrl(fileName)

	WIth fd(0) : .Name = "Selection" : .Value = UsedRangeCursor(oSheet) : End With
	' Disabled, because it conflicts with selection
	With fd(1) : .Name = "SinglePageSheets" : .Value = False : End With
	With fd(2) : .Name = "IsSkipEmptyPages" : .Value = True : End With

	If exportExt = "pdf" Then
		With args(0) : .Name = "FilterName" : .Value = "calc_pdf_Export" : End With
	ElseIf exportExt = "ods" Then
		With args(0) : .Name = "FilterName" : .Value = "calc8" : End With
	Else
		ErrorLocal$ = "FATAL: Export type '" & exportExt  & "' not handled"
	End If
	
	With args(1) : .Name = "FilterData" : .Value = fd : End With
	With args(2) : .Name = "Overwrite" : .Value = True : End With

	oDoc.storeToURL(fileUrl,  args)
	ExportAs = True
	Exit Function
ErrorHandler:
	ErrorLocal$ = "FATAL: ExportPDF: Unknown error"
End Function

Sub ListOfActiveCustomers()
	Dim oSheet, destSheet, cursor, oRange
	Dim startRow as Long
	Dim endRow as Long
	Dim startColumn as Long
	Dim endColumn as Long
	Dim requiredFields()
	Dim requiredFieldIndices() as Integer
	Dim iColumn as Integer, iRequiredField as Integer
	Dim headerCellStr as String

	oSheet = ThisComponent.Sheets(0)
	cursor = UsedRangeCursor(oSheet)

	' Skip Header
	startRow =  NaiveLastTable(cursor)
	endRow = cursor.RangeAddress.EndRow
	endColumn = cursor.RangeAddress.EndColumn
	' TODO Use data from PhoneNumber if some MobileNumber is missing
	requiredFields = Array("ConsumerNumber", "ConsumerName", "MobileNumber", "AreaCodeDesc", "LastDelivDate")
	'oSheet.Rows.removeByIndex(0, 3)

	For iColumn = startColumn To endColumn
		headerCellStr = oSheet.getCellByPosition(iColumn, startRow, iColumn, startRow).getString()
		For iRequiredField = 0 To UBound(requiredFields)
			If headerCellStr = requiredFields(iRequiredField) Then
				' TODO Allocate memory before hand and use a tracker index?
				ReDim Preserve requiredFieldIndices(UBound(requiredFieldIndices) + 1)
				requiredFieldIndices(UBound(requiredFieldIndices)) = iColumn
			End If
		Next iRequiredField
	Next iColumn
	destSheet = NewSheet(oDoc, "SBC Connection")
	
	Print Join(requiredFieldIndices)
	
	' TODO Ignore the Header Table if it exists
	' i.e. If two tables exists, assume the first one to be header table
	' and ignore it while copying to new sheet
	
	' Copy the cells in 'requiredFieldIndices' to 'destSheet'
End Sub

Sub CombineFiles(sFolder as String, fileRegex as String)
	Dim sFile
	Dim sFiles as Variant
	Dim i as Integer: i = 0
	Dim oDoc as Variant
	Dim dstSheet
	Dim oDstCursor
	Dim oSrcCursor
	Dim rangeAddress
	Dim oSheet
	If Not FileExists(sFolder) Then
		ErrorLocal$ = "sFolder path: '" & sFolder & "' does not exist"
		Exit Sub
	End If
	
	sFile = Dir( sFolder & "\" & fileRegex, 0)
	
	If  IsEmpty(oDoc) Then
		oDoc = ImportReportFile(sFolder & "\" & sFile, False)
		if IsEmpty(oDoc) Then
			ErrorLocal$ = "Failed to get Document for " & sInputFile
			Exit Sub
		End If
		If Not oDoc.supportsService( "com.sun.star.sheet.SpreadsheetDocument")  Then
			Print "The imported document is not a sheet document"
		End If
		dstSheet = oDoc.getSheets().getByIndex(0)
	End If
		
	sFile = Dir()
	Do While(sFile <> "")
		oDstCursor = UsedRangeCursor(dstSheet)
		i = i + 1

		oDoc.getSheets().insertNewByName(CStr(i), i)
		oSheet = oDoc.getSheets().getByIndex(i)
		If IsEmpty(oSheet) Then
			ErrorLocal$ = "Cannot create new sheet"
			Exit Sub
		End If
		
		oSheet.link(ConvertToUrl(sFolder & "\" & sFile), CStr(i),  CSV_FILTER_NAME,  PENDING_CSV_FILTER_OPTIONS, com.sun.star.sheet.SheetLinkMode.NORMAL)
		
		oSrcCursor = UsedRangeCursor(oSheet, 1)
		
		dstSheet.copyRange(dstSheet.getCellByPosition(0, oDstCursor.RangeAddress.EndRow + 1).getCellAddress(), oSrcCursor.RangeAddress)
		sFile = Dir()
	Loop
End Sub

Function UsedRangeCursor(oSheet as Variant, Optional rowsToSkip as Integer) as Variant
	Dim oCursor
	Dim i as Integer
	oCursor = oSheet.createCursor()
	oCursor.gotoStartOfUsedArea(False)
	If Not IsMissing(rowsToSkip) Then oCursor.gotoOffset(0, rowsToSkip, False)
	oCursor.gotoEndOfUsedArea(True)
	UsedRangeCursor = oCursor
End Function

Function GetProductNames() as Variant
	GetProductNames = Array( _
		5300, "14.2", _
		5350, "14.2s", _
	)
	' TODO finish deploying the extension and push extension to git
End Function

Function ProductDescrption(productCode as Integer) as String
	Dim i as Long
	Dim productNames: productNames = GetProductNames()
	ProductDescription = ""
	For i = 0 To UBound(productNames) Step 2
		If productNames(i) = productCode Then
			ProductDescription = productNames(i + 1)
		End If
	Next i
End Function

Function GetValueForKey(oRange as Variant, key as String, Optional valueOffset%) as Object
	' Returns a ScCellObj
	Dim oSearchRange
	Dim oSearchDescriptor
	Dim oCell

	If oRange.Columns.Count < 2 Then
		MsgBox "GetValueForKeyCannot have columns less than 2", 16
		GetValueForKey = oCell
		Exit Function
	End If
	
	oSearchRange = oRange.getCellRangeByPosition(0, 0, 0,  oRange.Rows.Count - 1)
	oSearchDescriptor = oSearchRange.createSearchDescriptor()
	With oSearchDescriptor
		.SearchString = key
		.SearchWords = True
		.SearchCaseSensitive = True
	End With
	oCell = oSearchRange.findFirst(oSearchDescriptor)

	If Not IsNull(oCell) Then
		If IsMissing(valueOffset) Then
			valueOffset = oCell.RangeAddress.StartColumn + 1
		End If
		oCell = oRange.getCellByPosition( valueOffset, _
			oCell.RangeAddress.StartRow _
		)
	End If
	GetValueForKey = oCell
End Function

Function UserFriendlyName(str as String) as String
	' Checks headerName and headerNameMatches for the string 'str',
	' If it's not available there, a naïve implementation adds spacing to 'str'
	Dim l as Long
	Dim c as String
	Dim i as Long
	Dim prevChar$
	Dim oValCell

	str = Trim(str)
	oValCell =  GetValueForKey(GlobalSondageSettings.oFieldAliasesRange, str)
	If Not IsNull(oValCell) Then
		UserFriendlyName = oValCell.String
		Exit Function
	End If
	
	l = Len(str)
	' Check with header "database"
	For i = 0 To l
		c = Mid(str, i + 1, 1)
		If i > 1 And (c > "A" And c < "Z") Then
				' Only prepend space if 'c' is not the first character...
				' or previous char doesn't have space
				UserFriendlyName = UserFriendlyName &  IIf(prevChar = " ", "", " ")  & c
		Else
			UserFriendlyName = UserFriendlyName & c
		End If
		prevChar = c
	Next
End Function

Sub SortColumn(ctx as SondageContext, columnName1 as String, Optional columnName2 as String)
	Dim iHeaderPos as Long
	Dim oSortFields(1) as new com.sun.star.util.SortField
	Dim oSortDesc(1) as new com.sun.star.beans.PropertyValue

	iHeaderPos = GetHeaderPosition(ctx, columnName1)
	If iHeaderPos = -1 Then
		Exit Sub
	End If


	' Area
	oSortFields(0).Field = iHeaderPos
	oSortFields(0).SortAscending = True

	' FIXME This should be handled from the sheet settings
	If Not IsMissing(columnName2) Then
		iHeaderPos = GetHeaderPosition(ctx, columnName2)
		If iHeaderPos = -1 Then
			Exit Sub
		End If
		oSortFields(1).Field = iHeaderPos
		oSortFields(1).SortAscending = True
	End If

	oSortDesc(0).Name = "SortFields"
    oSortDesc(0).Value = oSortFields
	oSortDesc(1).Name = "ContainsHeader"
	oSortDesc(1).Value = True
	
	ctx.oRange.Sort(oSortDesc)
End Sub

Function NewSheet(oDoc, sheetName as String) as Object
			Dim sheets as Object
			sheets = oDoc.Sheets()
			If Not sheets.hasByName(sheetName) Then
				sheets.insertNewByName(sheetName, sheets.getCount())
			End If
			NewSheet = sheets.getByName(sheetName)
End Function

Sub CleanColumnHeaders(ctx as SondageContext)
	Dim cell as Object
	Dim neatName as String
	Dim i as Integer
	For i = ctx.startColumn To ctx.endColumn
		cell = ctx.oSheet.getCellByPosition(i, ctx.headerRow)
		neatName = cell.getString()
		neatName = UserFriendlyName(neatName)
		cell.setString(neatName)
	Next
End Sub

Sub RemoveExtraMergeCells(oDoc as Object, oSheet as Object, oRangeAddress as Variant)
	Dim oRange as Object
	Dim oSortFields(0) as new com.sun.star.util.SortField
	Dim oSortDesc(0) as new com.sun.star.beans.PropertyValue
	Dim endRow as Long
	
	endRow = oRangeAddress.EndRow
	lastColumn = oRangeAddress.EndColumn
		
	rem set the range on which to sort'

	'oRange = oSheet.getCellRangeByName("A2:F20")
	oRange = oSheet.getCellRangeByPosition(0, 0, lastColumn, 0)
	oDoc.getCurrentController().select(oRange)
	initialColumnCount = oRange.Columns.getCount() - 1
	deletedColumns = 0
	For j = 0 To (initialColumnCount - deletedColumns)
		oCell = oRange.getCellByPosition(j, 0)
		con = oCell.String
		If con = "" Then
			oRange.Columns.removeByIndex(j, 1)
			deletedColumns = deletedColumns - 1
		Else
			Print con
		End If
	Next
End Sub

Sub UnFreezeSelection(oDoc as Object)
	Dim dispatcher as Object
	dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
	dispatcher.executeDispatch(oDoc.getCurrentController().getFrame(), ".uno:FreezePanes", "", 0, Array())
End Sub

Function GetHeaderPosition(ctx as SondageContext, searchString$, Optional isRoughHeaderMatch as Boolean) as Integer
	Dim iColumn as Integer
	Dim oCell as Object
	Dim cellString as String
	GetHeaderPosition = -1
	If IsMissing(isRoughHeaderMatch) Then isRoughHeaderMatch = False
	If searchString = "" Then
		Exit Function
	End If

	For iColumn = ctx.startColumn To ctx.endColumn
        oCell = ctx.oSheet.getCellByPosition(iColumn, ctx.headerRow)
        cellString = oCell.String
        If cellString = "" Then
        	'ErrorLocal$ = "BAD ARGUMENT: Cannot have empty columns within UsedRange, endColumn is " & CStr(endColumn)
        	Exit Function
        End If

		' TODO Implement regex matching
		If isRoughHeaderMatch = True Then
			If InStr(cellString, searchString) Then
				GetHeaderPosition = iColumn
				Exit Function
			End If
        ElseIf  cellString = searchString Then
            GetHeaderPosition = iColumn
            Exit Function
        End If
    Next iColumn
End Function

Function HighlightRowWithColumn(ctx as SondageContext, _
		highlightColumnName, highlightValue, Optional highlightColor as Long) as Long
	Dim currentStr as String
	Dim oCell as Object
	Dim oCellRange as Object
	Dim str as String
	Dim iSearchColumn as Long
	Dim i as Integer
	Dim highlightCount as Long
	
	If IsMissing(highlightColor) Then
		highlightColor = RGB(255, 255, 0)
	End If

	' Search for column position that has highlightBasedOn
	iSearchColumn = GetHeaderPosition(ctx, highlightColumnName)
	If iSearchColumn = -1 Then Exit Function
	For i = ctx.startRow To  ctx.endRow
		oCell = ctx.oSheet.getCellByPosition(iSearchColumn, i)
		If oCell.getString() = highlightValue Then
			oCellRange = ctx.oSheet.getCellRangeByPosition(0, i, ctx.endColumn, i)
			oCellRange.CellBackColor = highlightColor
			highlightCount = highlightCount + 1
		End If
	Next i
	HighlightRowWithColumn = highlightCount
End Function

Function ComputeOnRange(ctx as SondageContext, columnName as String, computeFunc%) as Long
	Dim headerPos
	Dim column
	Dim val
	headerPos = GetHeaderPosition(ctx, columnName)
	If headerPos = -1 Then
		ErrorLocal$ =  "Cannot find a column header that starts with '" & columnName & "'"
		Exit Function
	End If
	' TODO Check if the column we are searching, actually has date values.
	column = ctx.oSheet.getCellRangeByPosition(headerPos, 1, headerPos, ctx.endRow)
	ComputeOnRange =  column.computeFunction(computeFunc)
End Function

Sub ColumnJoin(joinChar$, idColumnName, dstCtx as SondageContext, dstColumnName$, srcCtx as SondageContext, srcColumnName$)
	Dim i&, j&
	Dim dstEndRow&, dstEndColumn%, srcEndRow&, srcEndColumn%
	Dim dstColumnIdx%, srcColumnIdx%
	Dim dstStr$, dstCell
	Dim dstRange, srcRange, srcRangeAddress, dstRangeAddress
	Dim oTextCursor, oService, statusBar
	statusBar = ThisComponent.CurrentController.StatusIndicator
	oService = CreateUNOService("com.sun.star.sheet.FunctionAccess")
	
	dstRange = UsedRangeCursor(dstCtx.oSheet)
	dstRangeAddress = dstRange.RangeAddress
	srcRange = UsedRangeCursor(srcCtx.oSheet)
	srcRangeAddress = srcRange.RangeAddress

	dstEndRow = dstRangeAddress.EndRow
	srcEndRow = srcRangeAddress.EndRow
	
	dstColumnIdx = GetHeaderPosition(dstCtx, dstColumnName)
	srcColumnIdx = GetHeaderPosition(srcCtx, srcColumnName)


	Dim srcColumnIdIdx: srcColumnIdIdx = GetHeaderPosition(srcCtx, idColumnName)
	Dim newSrcRange
	newSrcRange = srcSheet.getCellRangeByPosition(srcColumnIdIdx, srcCtx.startRow, srcCtx.endColumn, srcCtx.endRow)
	
	Dim dstColumnIdIdx: dstColumnIdIdx = GetHeaderPosition(dstCtx, idColumnName)

	statusBar.start("Merging Columns", 100)
	For i = dstStartRow To dstEndRow
		Dim srcCell
		Dim srcStr$
		Dim what$

		statusBar.setText("Merging " & CStr(i) & "/" & dstEndRow)
		statusBar.setValue((i / dstEndRow) * 100)

		dstCell = dstRange.getCellByPosition(dstColumnIdx, i)
		dstStr = dstCell.getText().String
		what = dstRange.getCellByPosition(dstColumnIdIdx, i).getText().String
		
		srcStr = oService.callFunction("VLOOKUP", Array(what, newSrcRange, srcColumnIdx, True))


		dstCell.getText().setString(dstStr & joinChar & srcStr)

		oTextCursor = dstCell.getText().createTextCursor()
	    oTextCursor.gotoStart(False)
	    oTextCursor.goRight(Len(dstStr), True)
	    'oTextCursor.CharWeight = com.sun.star.awt.FontWeight.BOLD
	    oTextCursor.goRight(1, False)
	    oTextCursor.gotoEnd(True)
	    oTextCursor.CharHeight = 7
	    srcStr = ""
	    what = ""
	Next
	statusBar.end()
End Sub

' TODO Use a general function that takes arrays
' and instead of the function ShortenDirections, use
' ReplaceArrays to make it more usable across other projects.
Sub ShortenDirections(ctx as SondageContext, columnIdx as Integer)
	'Shorten East as E. etc
	Dim toReplace() as String
	Dim toReplaceWith() as String
	Dim i as Long
	Dim oDescriptor
	Dim oColumn
	Dim columnToReplace
	oColumn = ctx.oSheet.getColumns().getByIndex(columnIdx)
	' TODO arrange it with convention
	toReplace() = Array("East", "West", "South", "North")
	toReplaceWith() = Array("E.", "W.", "S.", "N.")
	oDescriptor = oColumn.createReplaceDescriptor()
	For i = LBound(toReplace) To UBound(toReplace)
		With oDescriptor
			.SearchString = toReplace(i)
			.ReplaceString = toReplaceWIth(i)
		End With
		oColumn.replaceAll(oDescriptor)
	Next i
End Sub

Sub FilterColumn(ctx as SondageContext, filterColumnName as String, filterContent as Variant, Optional filterOperator as Variant, Optional filterUseRegex as Boolean)
	Dim oFilterDesc
	Dim filterRange, oRange
	Dim oCursor, o, oDescriptor
	'Dim oColumnHeader
	Dim newColumn : newColumn = ctx.endColumn + 1
	Dim oFields(0) as new com.sun.star.sheet.TableFilterField
	Dim filterCount as Long

	If IsMissing(filterOperator) Then filterOperator = com.sun.star.sheet.FilterOperator.EQUAL
	If IsMissing(filterUseRegex) Then filterUseRegex = False
	
	'On Error Goto ErrorHandler
	
	oRange = ctx.oSheet.getCellRangeByPosition(newColumn, 0, newColumn, ctx.endRow)
	'oColumnHeader = oRange.getCellByPosition(0, 0)
	'oColumnHeader.setString("0")	

	oDescriptor = ctx.oSheet.createReplaceDescriptor()

	filterRange = GetColumnRange(ctx, filterColumnName)
	oFilterDesc = filterRange.createFilterDescriptor(True)

	With oFields(0)
		.Field = filterRange.RangeAddress.StartColumn
		.IsNumeric = IsNumeric(filterContent)
		.Operator = filterOperator
		.StringValue = filterContent
		.NumericValue = filterContent
	End With

	oFilterDesc.setFilterFields(oFields())
	oFilterDesc.ContainsHeader = True
	oFilterDesc.UseRegularExpressions = filterUseRegex
	ctx.oSheet.filter(oFilterDesc)

	' TODO Check if there is a way to remove the 50,000 limit
	'oRange.fillSeries(com.sun.star.sheet.FillDirection.TO_BOTTOM, com.sun.star.sheet.FillMode.SIMPLE, 0, 1, 50000)
	'SortColumn(ctx.oSheet, 0, 1, newColumn, endRow, "0")

	'filterCount = oRange.computeFunction(com.sun.star.sheet.GeneralFunction.COUNT)	
	'ctx.oSheet.Rows.removeByIndex(filterCount, (ctx.endRow - filterCount) + 1)

'ErrorHandler:
	'ctx.oSheet.filter(ctx.oSheet.createFilterDescriptor(True))
	'ctx.oSheet.Columns.removeByIndex(newColumn, 1)
	'Reset
End Sub

Sub  SetHeader(ByRef oPageStyle, Optional sLeftHeader$, Optional sCenterHeader$, Optional sRightHeader)
	Dim oHeader
	Dim oText
	Dim oTextCursor

	oHeader = oPageStyle.RightPageHeaderContent
	
	If Not IsMissing(sLeftHeader) Then
		oText = oHeader.LeftText
		oTextCursor = oText.createTextCursor()
		oText.insertString(oTextCursor, sLeftHeader, true)
	End If
	
	If Not IsMissing(sCenterHeader) Then
		oText = oHeader.CenterText
		oTextCursor = oText.createTextCursor()
		oText.insertString(oTextCursor, sCenterHeader, true)
	End If
	
	If Not IsMissing(sRightHeader) Then
		oText = oHeader.RightText
		oTextCursor = oText.createTextCursor()
		oText.insertString(oTextCursor, sRightHeader, true)
	End If
	
	oPageStyle.RightPageHeaderContent = oHeader
End Sub
				
Sub SondageRestructureColumns(ctx as SondageContext, aColumnWidth as Variant)
	' columnWidthArray has values like Array(Array("Area", 0), Array("ID", 2000))
	' 0 means autofill
	Dim columnWidth, iField%
	Dim sField$, iWidth as Variant
	Dim oColumn
	Dim iHeaderColumn

	For iField = LBound(aColumnWidth) To UBound(aColumnWidth)
		sField = aColumnWidth(iField, 0)
		iWidth = aColumnWidth(iField, 1)

		If Not IsEmpty(iWidth) Then
			iHeaderColumn = GetHeaderPosition(ctx, sField)
			If iHeaderColumn = -1 Then
				If iWidth = -1 Then
					' No-Op as the field already does not exist
				ElseIf iWidth >= 0 Then
					SondageAppendColumn(ctx, sField)
				    iHeaderColumn = GetHeaderPosition(ctx, sField)
				Else
					ErrorLocal$ = "Cannot find: " & sField & " in headers": Exit Sub
				End If
			End If
	
			If iHeaderColumn <> -1 Then
				oColumn = ctx.oSheet.getColumns().getByIndex(iHeaderColumn)
				If iWidth = -1 Then
					'ctx.oSheet.getColumns().removeByIndex(iHeaderColumn, 1)
					oColumn.IsVisible = False
					'ctx.endColumn = ctx.endColumn - 1
				Else
					If iWidth = 0 Then
						oColumn.OptimalWidth = True
					Else
						oColumn.Width = iWidth
					End If
			End if
		End If
		End If
	Next iField
	ErrorLocal$ = ""
End Sub

Sub ReArrangeResultToHeader(ctx as SondageContext, Optional headerStyle$)
	' Assumptions kept local to this transform:
	' - row 1 is the first data/subtotal row; row 0 is left alone
	' - column A contains LibreOffice subtotal Result markers and group labels
	' - generated headers are written from column B through the last used column
	' - cells with style "Result" are subtotal rows
	' - the last Result row is the grand total, mirrored to the top and removed below
	' - one extra top row is for grand total, one is for the first subtotal header
	Dim startRow&, nRow&, nCol&, insertRow&, topRow&, totalRow&, removeRow&
	Dim oDoc, oRange, oUsedRangeAddress
	Dim resultRanges
	Dim oAddrs()
	Dim oAddr
	Dim oFound, oCells
	Dim insertRowCell
	Dim oSearchDesc

	If IsMissing(headerStyle) Then headerStyle =  "Accent 1"
	startRow = 1

	oUsedRangeAddress = UsedRangeCursor(ctx.oSheet).RangeAddress
	oRange = ctx.oSheet.getCellRangeByPosition(0, startRow, 0, oUsedRangeAddress.EndRow)

	oSearchDesc = oRange.createSearchDescriptor()
	oSearchDesc.SearchStyles = True
	oSearchDesc.SearchString = "Result"

	Dim sResult, sGroupBy
	Dim oRows, oCols, emptyValue as Object
	oRows = ctx.oSheet.getRows()
	oCols = ctx.oSheet.getColumns()
	Dim colRange

	' Construct first row and column to be same as others
	topRow = startRow
	totalRow = -1
	removeRow = -1
	oRows.insertByIndex(startRow, 2)
	oUsedRangeAddress.EndRow = oUsedRangeAddress.EndRow + 2
	insertRowCell = ctx.oSheet.getCellByPosition(0, startRow + 1)
	insertRowCell.CellStyle = "Result"
	startRow = startRow + 1

	oFound = ctx.oSheet.findFirst(oSearchDesc)
	Do While Not IsNull (oFound)
		'Print  "Name is: " & oFound.getText().getString()
		insertRow = startRow
		insertRowCell = ctx.oSheet.getCellByPosition(1, insertRow)
		startRow = oFound.RangeAddress.StartRow
		If startRow > oUsedRangeAddress.EndRow Then
			oFound = emptyValue
		Else
			sResult = ctx.oSheet.getCellByPosition(0, startRow).getText().String
			If sResult <> "" Then
				sGroupBy = ctx.oSheet.getCellByPosition(0, startRow - 1).getText().String
				colRange = ctx.oSheet.getCellRangeByPosition(1, insertRow, oUsedRangeAddress.EndColumn, insertRow)
				colRange.merge(True)
				colRange.CellStyle = headerStyle
				insertRowCell.getText().setString(sGroupBy & "   (" & sResult & ")")

				' Last Result row is the grand total; mirror it at the top and remove the bottom copy later.
				insertRowCell = ctx.oSheet.getCellByPosition(1, topRow)
				insertRowCell.getText().setString(sGroupBy & "   (" & sResult & ")")
				colRange = ctx.oSheet.getCellRangeByPosition(1, topRow, oUsedRangeAddress.EndColumn, topRow)
				colRange.merge(True)
				colRange.CellStyle = headerStyle
				totalRow = startRow
				removeRow = insertRow
			End If

			oRange = ctx.oSheet.getCellRangeByPosition(0, startRow, 0,  oUsedRangeAddress.EndRow)
			oFound = ctx.oSheet.findNext(oRange, oSearchDesc)
		End If
	Loop

	' Delete bottom-up so the first delete cannot shift the second row number.
	If totalRow > removeRow Then
		If totalRow <> -1 Then oRows.removeByIndex(totalRow, 1)
		If removeRow <> -1 Then oRows.removeByIndex(removeRow, 1)
	Else
		If removeRow <> -1 Then oRows.removeByIndex(removeRow, 1)
		If totalRow <> -1 Then oRows.removeByIndex(totalRow, 1)
	End If
	oCols.removeByIndex(0, 1)
End Sub














sub FiltersToCalc
	Dim oFF ' FilterFactory service
	Dim oFilterNames ' Array of filter names.
	Dim oDoc ' Document created to hold the filter names.
	Dim oSheet ' Sheet that will hold the filter information.
	Dim oCell ' Cell to update
	
	 Dim i% ' Index Variable.
	Dim fProps() ' Properties for each filter.
	Dim fp% ' Filter property index
	Dim fpCol% ' Column for the specified filter data.
	Dim s$ ' Work string that holds some property values.
	Dim iUserData% ' For enumerating array property values.
	Dim oProp ' A single property.
	Dim oArrayData ' Array of user properties.
	Dim sPropNames(7) As String
	Dim flags As Long
	sPropNames(0) = "Name"
	sPropNames(1) = "Import"
	sPropNames(2) = "Export"
	sPropNames(3) = "Options"
	sPropNames(4) = "Visible"
	sPropNames(5) = "Flags"
	sPropNames(6) = "DocumentService"
	sPropNames(7) = "UIName"
	oFF = createUnoService( "com.sun.star.document.FilterFactory" )
	oFilterNames = oFF.getElementNames()
	' Create a Calc doc and save the filter names to it.
	oDoc = StarDesktop.loadComponentFromURL( "private:factory/scalc", "_blank", 0, Array() )
	oSheet = oDoc.getSheets().getByIndex(0)
	' Print the filter names into a document.
	For i = LBound( oFilterNames ) To UBound( oFilterNames )
	fProps() = oFF.getByName(oFilterNames(i))
	For fp = LBound(fProps) To UBound(fProps)
	oCell = oSheet.getCellByPosition(fp, i+1)
	oProp = fProps(fp)
	fpCol = FindInArrayAdd(oProp.Name, sPropNames)
	If fpCol > UBound(sPropNames) Then
	ReDim Preserve sPropNames(fpCol) As String
	sPropNames(fpCol) = oProp.Name
	End If
	oCell = oSheet.getCellByPosition(fpCol, i+1)
	If Not IsArray(oProp.Value) Then
	oCell.setString(oProp.Value)
	If oProp.Name = "Flags" Then
	flags = oProp.Value
	oCell.setString(CStr(flags) & " = " & flags_int2str(flags))
	If flags and 1 Then
	oCell = oSheet.getCellByPosition(FindInArrayAdd("Import", sPropNames), i+1)
	oCell.setString("X")
	Endif
	If flags and 2 Then
	oCell = oSheet.getCellByPosition(FindInArrayAdd("Export", sPropNames), i+1)
	oCell.setString("X")
	Endif
	If flags and 128 Then
	 oCell = oSheet.getCellByPosition(FindInArrayAdd("Options", sPropNames), i+1)
	oCell.setString("X")
	Endif
	If ((flags and 4096) or (flags and 8192)) Then
	oCell = oSheet.getCellByPosition(FindInArrayAdd("Visible", sPropNames), i+1)
	oCell.setString("X")
	Endif
	End If
	ElseIf LBound(oProp.Value) <= UBound(oProp.Value) Then
	s = ""
	oArrayData = oProp.Value
	For iUserData = LBound(oArrayData) To UBound(oArrayData)
	If VarType(oArrayData(iUserData)) = 8 Then
	s = s & "(String:" & oArrayData(iUserData) & ")"
	Else
	s = s & "(" & oArrayData(iUserData).Name & ":" & oArrayData(iUserData).Value & ")"
	End If
	Next
	oCell.setString(s)
	End If
	Next
	Next
	For fp = LBound(sPropNames) To Ubound(sPropNames)
	oCell = oSheet.getCellByPosition(fp, 0)
	oCell.setString(sPropnames(fp))
	Next
	FinalFormat(oDoc)
End Sub
function flags_int2str(flags as long) as string
Dim cflags as long
Dim strval as string
Dim curFlag As Long
cflags = flags
strval = ""
if cflags and &H00000001 then
strval = strval + " Import"
cflags = cflags-1
endif
if cflags and &H00000002 then
strval = strval + " Export"
cflags = cflags-2
endif
if cflags and &H00000004 then
strval = strval + " Template"
cflags = cflags-4
endif
if cflags and &H00000008 then
strval = strval + " Internal"
cflags = cflags-8
endif

 if cflags and &H00000010 then
strval = strval + " TemplatePath"
cflags = cflags-16
endif
if cflags and &H00000020 then
strval = strval + " Own"
cflags = cflags-32
endif
if cflags and &H00000040 then
strval = strval + " Alien"
cflags = cflags-64
endif
if cflags and &H00000080 then
strval = strval + " UseOptions"
cflags = cflags-128
endif
if cflags and &H00000100 then
strval = strval + " Default"
cflags = cflags-256
endif
if cflags and &H00000200 then
strval = strval + " Executable"
cflags = cflags-512
endif
if cflags and &H00000400 then
strval = strval + " SupportSelection"
cflags = cflags-1024
endif
if cflags and &H00000800 then
strval = strval + " MapToAppPlug"
cflags = cflags-2048
endif
if cflags and &H00001000 then
strval = strval + " NotInFileDialog"
cflags = cflags-4096
endif
if cflags and &H00002000 then
strval = strval + " NotInChooser"
cflags = cflags-8192
endif
if cflags and &H00004000 then
strval = strval + " Acynchronas"
cflags = cflags-16384
endif
if cflags and &H00008000 then
strval = strval + " Creator"
cflags = cflags-32768
endif
if cflags and &H00010000 then
strval = strval + " Readonly"
cflags = cflags-65536
endif
if cflags and &H00020000 then

 strval = strval + " NotInstalled"
cflags = cflags-131072
endif
if cflags and &H00040000 then
strval = strval + " ConsultService"
cflags = cflags-262144
endif
if cflags and &H00080000 then
strval = strval + " 3rdPartyFilter"
cflags = cflags-524288
endif
if cflags and &H00100000 then
strval = strval + " Packed"
cflags = cflags-1048576
endif
if cflags and &H00200000 then
strval = strval + " SilentExport"
cflags = cflags-2097152
endif
if cflags and &H00400000 then
strval = strval + " BrowserPreferred"
cflags = cflags-4194304
endif
if cflags and &H00800000 then
strval = strval + " [H00800000]"
cflags = cflags-8388608
endif
if cflags and &H01000000 then
strval = strval + " [H01000000]"
cflags = cflags-16777216
endif
if cflags and &H02000000 then
strval = strval + " [H02000000]"
cflags = cflags-33554432
endif
if cflags and &H10000000 then
strval = strval + " Preferred"
cflags = cflags-268435456
endif
if cflags <> 0 then
strval = strval + " !!! ATTENTION: unsupported flag ["+cflags+"] detected !!!"
endif
flags_int2str = strval
end function
Function FindInArrayAdd(sName$, nameArray) As Integer
Dim i As Integer
For i = LBound(nameArray()) To UBound(nameArray())

 'Print nameArray(i) & " and " & sName
If nameArray(i) = sName Then
FindInArrayAdd = i
Exit Function
End If
Next
i = UBound(nameArray()) + 1
FindInArrayAdd = i
End Function
sub FinalFormat(oDoc)
rem ----------------------------------------------------------------------
rem define variables
Dim document as object
Dim dispatcher as object
rem ----------------------------------------------------------------------
rem get access to the document
document = oDoc.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
rem ----------------------------------------------------------------------
Dim args1(0) as new com.sun.star.beans.PropertyValue
args1(0).Name = "ToPoint"
args1(0).Value = "$A$1"
dispatcher.executeDispatch(document, ".uno:GoToCell", "", 0, args1())
rem ----------------------------------------------------------------------
Dim args2(1) as new com.sun.star.beans.PropertyValue
args2(0).Name = "By"
args2(0).Value = 1
args2(1).Name = "Sel"
args2(1).Value = true
dispatcher.executeDispatch(document, ".uno:GoRightToEndOfData", "", 0, args2())
rem ----------------------------------------------------------------------
Dim args3(2) as new com.sun.star.beans.PropertyValue
args3(0).Name = "FontHeight.Height"
args3(0).Value = 12
args3(1).Name = "FontHeight.Prop"
args3(1).Value = 100
args3(2).Name = "FontHeight.Diff"
args3(2).Value = 0
dispatcher.executeDispatch(document, ".uno:FontHeight", "", 0, args3())
rem ----------------------------------------------------------------------
Dim args4(0) as new com.sun.star.beans.PropertyValue
args4(0).Name = "Bold"
args4(0).Value = true
dispatcher.executeDispatch(document, ".uno:Bold", "", 0, args4())

rem ----------------------------------------------------------------------
Dim args5(0) as new com.sun.star.beans.PropertyValue
args5(0).Name = "HorizontalAlignment"
args5(0).Value = com.sun.star.table.CellHoriJustify.CENTER
dispatcher.executeDispatch(document, ".uno:HorizontalAlignment", "", 0, args5())
rem ----------------------------------------------------------------------
Dim args6(1) as new com.sun.star.beans.PropertyValue
args6(0).Name = "By"
args6(0).Value = 1
args6(1).Name = "Sel"
args6(1).Value = true
dispatcher.executeDispatch(document, ".uno:GoDownToEndOfData", "", 0, args6())
rem ----------------------------------------------------------------------
Dim args7(0) as new com.sun.star.beans.PropertyValue
args7(0).Name = "aExtraWidth"
args7(0).Value = 254
dispatcher.executeDispatch(document, ".uno:SetOptimalColumnWidth", "", 0, args7())
rem ----------------------------------------------------------------------
Dim args8(8) as new com.sun.star.beans.PropertyValue
args8(0).Name = "ByRows"
args8(0).Value = true
args8(1).Name = "HasHeader"
args8(1).Value = true
args8(2).Name = "CaseSensitive"
args8(2).Value = false
args8(3).Name = "IncludeAttribs"
args8(3).Value = true
args8(4).Name = "UserDefIndex"
args8(4).Value = 0
args8(5).Name = "Col1"
args8(5).Value = 7
args8(6).Name = "Ascending1"
args8(6).Value = true
args8(7).Name = "Col2"
args8(7).Value = 1
args8(8).Name = "Ascending2"
args8(8).Value = true
dispatcher.executeDispatch(document, ".uno:DataSort", "", 0, args8())
dispatcher.executeDispatch(document, ".uno:GoToCell", "", 0, args1())
end sub

