'Copyright 2023-2025 Bharatvaj Hemanth <bharatvaj@yahoo.com>

'Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

'1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

'2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
'disclaimer in the documentation and/or other materials provided with the distribution.

'3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
'products derived from this software without specific prior written permission.

'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND
'ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
'WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
'DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
'FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
'DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
'SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
'AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
'(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
'SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'Option VBASupport 1
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 GlobalSondageSettings as New SondageSettings

' Options read from sheet

Private orgCode As String
Private exportPrefix As String
' Allowed values,
' EKYC, PENDING, INSPECTION,  SBC, POPULATE
'The number of columns that are copied and the column size will be affected
Private reportType As String
Private inputType As String
'Holds filter information such as ONLINE
Private reportFilter As String
' The days below 'thorgCodee maximum date in report' to show as bad
Private priorityThreshold As Integer
Private highlightColor As Long
Private priorityColor As Long
Private isHeadless As Boolean
Private isDBRequired as Boolean
' True if you want to create sheets with Area specific data
Private enableGroupReports As Boolean
Private organizeInputsFolder as String
Private removeInputFileAfterSuccess as Boolean
Private gvtSoftwareFolder$
Private debugInputFile$
Private customerDBFile$
Private shouldSyncWithGVT as Boolean
Private ErrorLocal$
Private pendingRemarksValidateList$
Private ekycRemarksList$

Private stateName As String
Private cityName As String

Global Const highlightBasedOn = "Payment Option" ' A yellow background is drawn that matches this column and 'highlightSearchString'
Global Const highlightSearchString = "Online" ' Does partial match
Global Const highlightRemoveColumn = True ' True if you want remove the column once the highlight is done
Global Const shouldRunSubtotals = True
Global Const shouldExportPDF = True ' If True this will export all the created sheets with Area specific data individually TODO change name to easily understand
Global Const shouldExportSummaryEditable = True ' If True this will export summary editable
'Private shouldExportSummaryPDF as Boolean' If True the first page will be exported as PDF
Global Const shouldCreateDataPivot = False
Global Const CURRENCY_UNIT = ""

Global Const CSV_FILTER_NAME = "Text - txt - csv (StarCalc)"

' Refer https://help.libreoffice.org/latest/en-US/text/shared/guide/csv_params.html
Global Const PENDING_CSV_FILTER_OPTIONS = "44,34,76,1,5/9/6/4/7/1/8/9/9/9/10/9"
' Values are loaded from the document
' Move all these to SondageContext? Which contain sheet, {start,end}{Column,Row} and others common things
Private tillDate As Date
Private tillDateStr As String
Private fromDate As Date
Private fromDateStr As String
Private sheetNameSuffix As String
Private exportDestDir As String

Sub CleanupProductCode(oSheet as Object, endColumn as Long, endRow as Long)
	MsgBox "Not implemented: productNames"
End Sub

Sub IterateTableAndAct()
	' Call it Sub-table in Sondage
	' Segregate Sondage as sondage-basic, sondage-db, etc?
	Dim oDoc, oSheet, oCell
	Dim iRow&, startColumn%
    Dim oCursor As Object
    Dim oTableRange As Object
    Dim nLastRow As Long
    Dim nRow As Long
    Dim tableCount As Integer
    
    oDoc = ReturnComponentIfOpen("C:\Users\bhara\Downloads\ViewTransactionDetail.csv")
    If IsNull(oDoc) Then
    	Print "Error opening Transaction Details"
    	Exit Sub
    End If
    oSheet = oDoc.getSheets().getByIndex(0)
    
    ' 1. Find the final used row on the entire sheet to know when to stop looping
    oCursor = oSheet.createCursor()
    oCursor.gotoEndOfUsedArea(False)
    nLastRow = oCursor.RangeAddress.EndRow
    
    tableCount = 0
    nRow = 0
    
    ' 2. Loop down Column A to find individual tables
    Do While nRow <= nLastRow
        oCell = oSheet.getCellByPosition(0, nRow)

        If oCell.Type <> com.sun.star.table.CellContentType.EMPTY Then
            tableCount = tableCount + 1
            oCursor = oSheet.createCursorByRange(oCell)
            oCursor.collapseToCurrentRegion() 
			oTableRange = oCursor.RangeAddress

            'MsgBox "Found Table " & tableCount & " at Range: " & oTableRange.StartRow

            Dim oCurrentCell, sCurrentCell
            oCurrentCell = oSheet.getCellByPosition(oTableRange.startColumn, oTableRange.startRow)
            sCurrentCell = oCurrentCell.getString()
            If InStr(sCurrentCell, "ConsumerNumber") Then
            	Act1(oSheet, oTableRange)
            End If

            nRow = oCursor.RangeAddress.EndRow + 1
        Else
            ' Move to the next row if this one is empty
            nRow = nRow + 1
        End If
    Loop
    
    MsgBox "Finished! Total tables found: " & tableCount
End Sub

Function SondageContextSetRange(ByRef ctx as SondageContext, oRangeAddr, Optional hasHeader as Boolean)
	If IsMissing(hasHeader) Then hasHeader = True
	ctx.headerRow = oRangeAddr.StartRow
	ctx.startColumn = oRangeAddr.startColumn
	ctx.startRow = IIf(hasHeader, oRangeAddr.StartRow + 1, oRangeAddr.StartRow)
	ctx.endColumn = oRangeAddr.endColumn
	ctx.endRow = oRangeAddr.endRow
End Function

Function Act1(oSheet, oRangeAddr)
	Dim ctx as SondageContext
	Dim iRow&
	Dim iMainColumn%
	ctx.oSheet = oSheet
	SondageContextSetRange(ctx, oRangeAddr)
	' TODO Make this more flexible with regex, so this can
	' be set easily in the sheet
	iMainColumn = GetHeaderPosition(ctx, "ConsumerNumber", True)

	If iMainColumn = -1 Then Exit Function
	For iRow = ctx.startRow To ctx.endRow
		Print ctx.oSheet.getCellByPosition(iMainColumn, iRow).getString()
	Next iRow
End Function

Function CreatePivotForRefill(ByRef ctx as SondageContext, ByRef sonConf as SondageConfiguration, oDestSheet)
	Dim oTables, oTDescriptor, oFields, oField, iField%
	Dim oCellAddress as new com.sun.star.table.CellAddress

	oCellAddress.Sheet = oDestSheet
	oCellAddress.Column = 0
	oCellAddress.Row = 0
	
	oTables = ctx.oSheet.getDataPilotTables()
	oTDescriptor = oTables.createDataPilotDescriptor()
	oTDescriptor.setSourceRange(ctx.oRange.getRangeAddress())

	oFields = oTDescriptor.getDataPilotFields()
	
	iField = GetHeaderPosition("Operator Name")
	oField = oFields.getByIndex(iField)
	oField.Orientation = com.sun.star.sheet.DataPilotFieldOrientation.ROW
	
	iField = GetHeaderPosition("Type")
	oField = oFields.getByIndex(iField)
	oField.Orientation = com.sun.star.sheet.DataPilotFieldOrientation.COLUMN

	iField = GetHeaderPosition("Cylinder Qty")
	oField = oFields.getByIndex(iField)
	oField.Orientation = com.sun.star.sheet.DataPilotFieldOrientation.DATA
	oField.Function = com.sun.star.sheet.GeneralFunction.SUM
	
	oTables.insertNewByName("REFILLDataPilot", oCellAddress, OTDescriptor)
End Function

Function ReadSettings() as Boolean	
	Dim oDoc
	Dim oSheet
	Dim rangeAddress
	Dim oRange
	ReadSettings = False
	
	oSheet = ThisComponent.Sheets.getByName("Settings")
	rangeAddress = UsedRangeCursor(oSheet).RangeAddress
	oRange = oSheet.getCellRangeByPosition(0, 0, rangeAddress.EndColumn, rangeAddress.EndRow)

	isHeadless = True
	' Organization Details
	orgCode = GetValueForKey(oRange, "OrgCode").String
	stateName = GetValueForKey(oRange, "StateName").String
	cityName = GetValueForKey(oRange, "CityName").String
	highlightColor = GetValueForKey(oRange, "HighlightColor").CellBackColor
	reportType = GetValueForKey(oRange, "ReportType").String
	reportFilter = GetValueForKey(oRange, "ReportFilter").String
	exportPrefix = GetValueForKey(oRange, "ExportFolder").String
	priorityThreshold = CInt(GetValueForKey(oRange, "PriorityThreshold").String)
	priorityColor = GetValueForKey(oRange, "PriorityColor").CellBackColor
	enableGroupReports = CBool(GetValueForKey(oRange, "EnableGroupReports").String)
	organizeInputsFolder = GetValueForKey(oRange, "OrganizeInputsFolder").String
	removeInputFileAfterSuccess = CBool(GetValueForKey(oRange, "RemoveInputFileAfterSuccess").String)
	gvtSoftwareFolder = GetValueForKey(oRange, "GVTSoftwareFolder").String
	debugInputFile = GetValueForKey(oRange, "DebugInputFile").String
	customerDBFile = GetValueForKey(oRange, "CustomerDBFile").String
	shouldSyncWithGVT = GetValueForKey(oRange, "ShouldSyncWithGVT").String
	pendingRemarksValidateList = GetValueForKey(oRange, "PendingRemarksValidateList").String
	ekycRemarksList = GetValueForKey(oRange, "EkycRemarksList").String
	' Skip check if the path is not given
	If shouldSyncWithGVT Then
		If Not FileExists(gvtSoftwareFolder) Then
			MsgBox "Please enter correct one and rerun the macro", 16, "Given GVT Advance Path does not exist"
			Exit Function
		End If
	End If

	'If IsNull(oCell) Then
	'	MsgBox "Setting not found, throw error"
	'	Exit Sub
	'End If
	ReadSettings = True
End Function

Function CreateValidationList(ctx as SondageContext, columnName$, sValidationList)
	Dim oValidation, oRange, oCell
	Dim aItems, sFirstItem$,finalFormula$
	oRange = GetColumnRange(ctx, columnName)

	Dim listDelim: listDelim = CHR(10)

	oValidation = oRange.Validation
	oValidation.Type =  com.sun.star.sheet.ValidationType.LIST
	aItems = Split(sValidationList, listDelim)

	If LBound(aItems) <> -1 Then
		sFirstItem = aItems(LBound(aItems))
	Else
		sFirstItem = sValidationList
	End If

	oCell = oRange.getCellByPosition(0, 0)
	oCell.setString(sFirstItem)
	
	oRange.fillSeries(com.sun.star.sheet.FillDirection.TO_BOTTOM, com.sun.star.sheet.FillMode.SIMPLE, 0, 0, ctx.endRow)

    finalFormula = """" & Join(Split(sValidationList, listDelim), """;""") & """"
	oValidation.setFormula1(finalFormula)
	oRange.Validation = oValidation
End Function

Function ValidateDoc(oDoc as Object, docType$) as String
	Dim _err$ : _err = ""
	if IsEmpty(oDoc)Then
		_err = "Failed to get Document for " & sInputFile
	ElseIf Not oDoc.supportsService(docType) Then
		_err = sInputFile & " is not a valid Spreadsheet Document"
	ElseIf oDoc.CurrentController.ViewControllerName = "PrintPreview" Then
		_err = "Cannot run this macro in 'Print Preview', please close it and try again"
	End If
	ValidateDoc = _err
End Function

Function AssertColumn(ctx as SondageContext, sCol$) as Boolean
	Dim iCol%
	AssertColumn = True
	iCol =  GetHeaderPosition(ctx, sCol)
	If iCol = -1 Then
		ErrorLocal$ = "Cannot proceed, " & sCol & " column is " & iCol
		AssertColumn = False
	End If
End Function

Function SondageAppendColumn(ByRef ctx as SondageCtx, sColumnName$)
		Dim oCell
		Dim oRange
		ctx.endColumn = ctx.endColumn + 1
		'ctx.oSheet.getColumns().insertByIndex(ctx.endColumn, 1)
		oCell = ctx.oSheet.getCellByPosition(ctx.endColumn, 0)
		oCell.setString(sColumnName)
		oRange = GetColumnRange(ctx, sColumnName)
		oCell.CellStyle = "Heading 1"
End Function

Function GetColumnSettings(sheetName$) as Boolean
	Dim oDoc, oSheet
	GetColumnSettings = False
	oDoc = ThisComponent
	oSheet = oDoc.getSheets().getByName(sheetName)
	If IsNull(oSheet) Then Exit Function
End Function

Function SondageGetContext(oSheet as Variant) as SondageContext
	Dim ctx as New SondageContext
	ctx.oSheet = oSheet
	ctx.oDoc = oSheet.DrawPage.Forms.Parent
	ctx.oRange = UsedRangeCursor(oSheet)
	ctx.headerRow = 0
	ctx.startColumn = 0
	ctx.startRow = 1
	ctx.endRow = ctx.oRange.RangeAddress.EndRow
	ctx.endColumn = ctx.oRange.RangeAddress.EndColumn
	SondageGetContext = ctx
End Function

Function SondageJoinVertical(ctx as SondageContext, sIdColumn$)
    Dim i&: i = 1
    Dim iIdColumn%: iIdColumn = GetHeaderPosition(ctx, sIdColumn)
    ' TODO Add mismatching content as array, rather than discarding them entirely
    For i = ctx.startRow To ctx.endRow
        With ctx.oSheet
            If .getCellByPosition(iIdColumn, i).String = .getCellByPosition(iIdColumn, i + 1).String Then
                .getRows().removeByIndex(i + 1, 1)
                ctx.endRow = ctx.endRow - 1
            End If
        End With
    Next
End Function

Function RemoveRows(ByRef ctx as SondageContext, rowsToRemove&)
	If rowsToRemove <> 0 Then
		ctx.oSheet.getRows().removeByIndex(0, rowsToRemove + 1)
		' FIXME Check this calculation again, this could be reason, West Mambalam is
		' not appearing on the list sometimes
		ctx.endRow = ctx.endRow - (rowsToRemove + 1)
	End If
End Function

Function SondageConditionalHorizontalCopy(ctx as SondageContext, sDstColumn$, sSrcColumn$)
    iSrcColumn = GetHeaderPosition(ctx, sSrcColumn)
    iDstColumn = GetHeaderPosition(ctx, sDstColumn)

    Dim i&: i = 1
    ' Remove duplicates, Move value from 'Phone' if "Mobile' has no value
    For i = ctx.startRow To ctx.endRow
    With ctx.oSheet
        If .getCellByPosition(iDstColumn, i).Value = 0 Then
            .getCellByPosition(iDstColumn, i).Value = .getCellByPosition(iSrcColumn, i).Value
        End If
    End With
    Next i
End Function

Function SondageInit(oDoc)
	Dim oFieldAliasesSheet as Variant
	oFieldAliasesSheet = oDoc.getSheets().getByName("FieldAliases")

	GlobalSondageSettings.oFieldAliasesRange = UsedRangeCursor(oFieldAliasesSheet)
End Function

Function SondageGetPropVal(aContainer, sProp$, Optional sDefaultValue) as String
	Dim oParent
	On Error Goto ErrorHandler
	For Each oParent In aContainer
		     If oParent.Name = sProp Then
		     	SondageGetPropVal = oParent.Value
		     	Exit Function
		     End If
	Next oParent
	ErrorHandler:
	If Not IsMissing(sDefaultValue) then SondageGetPropVal = sDefaultValue
End Function

Function SondageReflectionQuickAccess(aContainer, sProp$, oVal, Optional callByNameArg%) as Variant
	Dim oParent
	If IsMissing(callByNameArg) Then callByNameArg = 2 ' 2 = Get operation	
	On Error Goto ErrorHandler
	For Each oParent In aContainer
	        Dim propertyValue
		    propertyValue = CallByName(oParent, sProp, callByNameArg)  
		     If propertyValue = oVal Then
		     	SondageReflectionQuickAccess = oParent
		     	Exit Function
		     End If
	Next oParent
	ErrorHandler:
End Function

Function GetHeaderIndex(aHeader, sProperty$) as Long
	Dim i%
	GetHeaderIndex = -1
	For i = LBound(aHeader) To UBound(aHeader)
		If aHeader(i) = sProperty Then
			GetHeaderIndex = i
			Exit Function
		End If
	Next i
End Function

Function SondageTransformSheet(ctx, sonConf, reportType, sWidthColumn$)
	Dim i%, iWidthColumn%, sWidth$
	Dim sField$
	Dim aReports, oReport

	aReports = sonConf.Reports
	oReport = SondageReflectionQuickAccess(aReports, "Title", reportType)

	' TODO Throw error
	If IsEmpty(sonConf) Then Exit Function

	iWidthColumn = GetHeaderIndex(sonConf.Headers, sWidthColumn)

	Dim aColumns2D(UBound(oReport.Fields), 1)
	For i = 0 To UBound(oReport.Fields)
		sField = oReport.Fields(i).Field
		aColumns2D(i, 0) = oReport.Fields(i).Field
		sWidth = oReport.Fields(i).Values(iWidthColumn)
		If sWidth <> "" Then
			aColumns2D(i, 1) = CLng(sWidth)
		End If
	Next i
	SondageRestructureColumns(ctx, aColumns2D)
End Function

Sub _SondageTransformSheet(ctx, reportType$)
	Dim oDoc
	'TODO This should be set through GroupHeader logic
	oDoc = ctx.oDoc

	If reportType = "PENDING" Then
		ApplyTheme(oDoc, "millennium.ots")
		RemoveColumnsExcept(ctx, Array( _
			"Area", _
			"Address", _	
			"ID", _
			"Name", _
			"Mobile", _
			"Book", _
			"Payment Option", _
			"Code" _
		))

		SetWidths(ctx, Array( _
				Array("Area", 0), _
				Array("ID", 0), _
				Array("Code", 1000), _
				Array("Name", 7000), _
				Array("Mobile", 0), _
				Array("Book", 0) _
		))
	ElseIf reportType = "INSPECTION" Then
			ApplyTheme(oDoc, "green_grapes.ots")
			RemoveColumnsExcept(ctx, Array( _
				"Area", _
				"ID", _
				"Name", _
				"Address", _
				"Mobile" _
			))
	ElseIf reportType = "TUBE" Then
			ApplyTheme(oDoc, "pumpkin.ots")
			endColumn = RemoveColumnsExcept(ctx, Array( _
				"Area", _
				"ID", _
				"Name", _
				"Address", _
				"Mobile" _
	))
	ElseIf reportType = "REFILL" Then
		ApplyTheme(oDoc, "pumpkin.ots")
		RemoveColumnsExcept(ctx, Array( _
				"ID", _
				"Name", _
				"Code", _
				"Operator Name" _
			))
			'"Block Reason" _
		SetWidths(ctx, Array( _
				Array("ID", 0), _
				Array("Name", 3000), _
				Array("Code", 2000), _
				Array("Operator Name", 4000) _
		))
	ElseIf reportType = "DORMANT" Then
		ApplyTheme(oDoc, "pumpkin.ots")
		RemoveColumnsExcept(ctx, Array( _
				"Area", _
				"ID", _
				"Name", _
				"Address", _
				"Mobile" _
			))
			'"Block Reason" _
			SetWidths(ctx, Array( _
				Array("Area", 1000), _
				Array("ID", 0), _
				Array("Name", 3000), _
				Array("Address", 8000), _
				Array("Mobile", 2000) _
			))
	ElseIf reportType = "SBC"Then
		ApplyTheme(oDoc, "pumpkin.ots")
		RemoveColumnsExcept(ctx, Array( _
				"ID", _
				"Name", _
				"Address", _
				"Mobile", _
				"Area", _
				"No Of Cylinder" _
			))
			SetWidths(ctx, Array( _
				Array("ID", 0), _
				Array("Name", 3000), _
				Array("Address", 8000), _
				Array("Mobile", 0), _
				Array("Area", 0) _
			))
		ElseIf reportType = "EKYC" Then
			ApplyTheme(oDoc, "nature.ots")
			enableGroupReports = True

			RemoveColumnsExcept(ctx, Array( _
				"Area", _
				"ID", _
				"Name", _
				"Address", _
				"Mobile" _
			))
			SetWidths(ctx, Array( _
				Array("Area", 2000), _
				Array("ID", 0), _
				Array("Name", 3000), _
				Array("Address", 8500), _
				Array("Mobile", 2000) _
			))
		ElseIf reportType = "VIP" Then
			ApplyTheme(oDoc, "green_grapes.ots")
			RemoveColumnsExcept(ctx, Array( _
				"Area", _
				"ID", _
				"Name", _
				"Address", _
				"Mobile" _
			))
			SetWidths(ctx, Array( _
				Array("Area", 0), _
				Array("ID", 0), _
				Array("Name", 3000), _
				Array("Address", 8000), _
				Array("Mobile", 0) _
			))
		Else
			ErrorLocal$ = "Unknown reportType: '" & reportType & "'"
			Exit Sub
	End If
End Sub

Function SegregateEKYCDoneOnline()
	' Array
End Function

Sub Main(Optional sInputFiles as Variant)
	Dim aInputFiles, sInputFile$
	Dim aDoc as Variant, oDoc, oDBDoc, oDispatcher
	Dim oOrigSheet, oSheet, oDBSheet, oSheets as Object
	Dim oCursor, oTextCursor
	Dim sonConf, sonReport, aSettings

	Dim sTheme$, badStyleName$
	Dim idColumn%, mobileColumn%, phoneColumn%, addressColumn%, nameColumn%
	Dim groupByColumn%, areaNames as New Collection
	Dim rowsToRemove%
	Dim highlightedCount as Integer, formatNum as Integer
	Dim idRange, bookRange, nameRange
	Dim dColumns as Object
	Dim headerRange as Object
	Dim statusBar as Variant
	Dim ctx as New SondageContext
	Dim dbCtx as New SondageContext
	Dim sGroupBy$, iGroupByColumn%

	Dim cellRangeToCopy as Object
	Dim pageStyle as Object
	Dim oLocale as new com.sun.star.lang.Locale
	
	' Setup args
	aInputFiles = Split(sInputFiles, ";")

	' Initialize Globals
	SondageInit(ThisComponent)
	If Not ReadSettings() Then Exit Sub
	' TODO Move this to read settings?
	sonConf = SondageParseFieldConfiguration()
	If ErrorLocal$ <> "" Then Goto ErrorHandler

	' Use today's date without rounding the time into tomorrow.
	tillDate = Date()
	badStyleName = "T4"
	enableGroupReports = True

	For Each sInputFile in aInputFiles
		If IsMissing(sInputFile) Or TypeName(sInputFile) <> "String" Then
			If debugInputFile <> "" Then
				sInputFile = debugInputFile
				isHeadless = False
			Else
				MsgBox "Please give an input file", 16, "No input given"
				GoTo FinalFallback
			End If
		End If
	Next sInputFile
	
	sInputFile = aInputFiles(0)

	sonReport = SondageInferDocumentType(sonConf.Reports, aInputFiles)
	If IsEmpty(sonReport) Then
		ErrorLocal = "Cannot infer report configuration for '" & sInputFile & "'"
		Goto ErrorHandler
	End If
	inputType = sonReport.Title

	If reportType = "AUTO" Then
		reportType = inputType
	End If

	aSettings = sonReport.Settings
	sGroupBy = SondageGetPropVal(aSettings, "GroupBy")

	'If reportType = "PENDING" Then
	'	isDBRequired = True
	'End If

	If isDBRequired Then
		oDBDoc = SondageImportFile(sonReport, customerDBFile, "com.sun.star.sheet.SpreadsheetDocument", True, False, True)
		If ErrorLocal$ <> "" Then Goto ErrorHandler
	End If
	
	' FIXME The isHidden = False value is hardcoded, but use value from settings
    aDoc = SondageImportFiles(sonReport, aInputFiles, "com.sun.star.sheet.SpreadsheetDocument", True, False)
	If ErrorLocal$ <> "" Then Goto ErrorHandler
	oDoc = aDoc(0)
	statusBar = oDoc.CurrentController.StatusIndicator

	If oDoc.CurrentController.hasFrozenPanes() Then
		Call UnFreezeSelection(oDoc)
	End If

	ctx = SondageGetContext(oDoc.Sheets(0))

	If ctx.oSheet.IsProtected Then
		ctx.oSheet.Unprotect(reportType)
	End If

	' EKYC starts with its header on line 1; never discard it as a preamble.
	If reportType <> "EKYC" Then
		rowsToRemove = NaiveLastTable(ctx)
		RemoveRows(ctx, rowsToRemove)
	End If

	'If oDoc.Sheets.Count <> 1 Then oDoc.Sheets.removeByName("CONSUMERSWorkingCopy")

	' Copy the first, sheet if there is only one sheet in document
	If oDoc.Sheets.Count = 1 Then
		If shouldCreateDataPivot = False Then
			oDoc.Sheets.copyByName(ctx.oSheet.Name, reportType & "WorkingCopy", 1)
		End If
	End If

	oDoc.lockControllers()
	' Register Styles
	SetCustomBadStyle(oDoc, oLocale, badStyleName) : If ErrorLocal$ <> "" Then Goto ErrorHandler

	ctx.oSheet.Protect(reportType)

	If isDBRequired Then
		dbCtx = SondageGetContext(oDBDoc.Sheets(0))
		Call CleanColumnHeaders(dbCtx)
	End If

	ctx = SondageGetContext(oDoc.Sheets(1))

	If ctx.oSheet.Name = reportType & "WorkingCopy" Then
		' It's not possible to create a style even if only one sheet is blocked
		Call CleanColumnHeaders(ctx)
	End If

	iGroupByColumn = GetHeaderPosition(ctx, sGroupBy)
	If iGroupByColumn = -1 Then
		ErrorLocal$ = "Cannot proceed, '" & sGroupBy & "' column not found"
		Goto ErrorHandler
	End If
	If iGroupByColumn > 0 Then
		ctx.oSheet.getColumns().insertByIndex(0, 1)
		ctx.oSheet.moveRange(ctx.oSheet.getCellByPosition(0, 0).CellAddress, _
			ctx.oSheet.getCellRangeByPosition(iGroupByColumn + 1, 0, iGroupByColumn + 1, ctx.endRow).RangeAddress)
		ctx.oSheet.getColumns().removeByIndex(iGroupByColumn + 1, 1)
		ctx = SondageGetContext(ctx.oSheet)
	End If

	' FIXME Enable normal Consumer List Generation Later
	 If shouldSyncWithGVT Then
		ReducedPopulateConsumerDetails(gvtSoftwareFolder, ctx.oSheet)
		'PopulateConsumerDetails(gvtSoftwareFolder, ctx.oSheet)
		GoTo FinalFallback
	End If

	'Call CleanupProductCode(ctx, endRow)

	' Filter - Remove unrequired fields
	If reportType = "INSPECTION" Then
		Call FilterColumn(ctx, "Area", orgCode & "_PortIn", com.sun.star.sheet.FilterOperator.NOT_EQUAL)
		Call FilterColumn(ctx, "Inspection Due Now", "Over Due")
		Call FilterColumn(ctx, "Mobile", 0, com.sun.star.sheet.FilterOperator.NOT_EQUAL)
	ElseIf reportType = "TUBE" Then
		Call FilterColumn(ctx, "Area", orgCode & "_PortIn", com.sun.star.sheet.FilterOperator.NOT_EQUAL)
		Call FilterColumn(ctx, "Tube Change Due Now", "Over Due")
		Call FilterColumn(ctx, "Mobile", 0, com.sun.star.sheet.FilterOperator.NOT_EQUAL)
	ElseIf reportType = "VIP" Then
		Call FilterColumn(ctx, "Category", "VIP")
	ElseIf reportType = "DORMANT" Then
		Call FilterColumn(ctx, "Block Reason", "Dormant")
	ElseIf reportType = "REFILL" Then
		Call FilterColumn(ctx, "Type", "Domestic", com.sun.star.sheet.FilterOperator.NOT_EQUAL)
	End If

	' Expensive Operation, run after filter
	If inputType = "CONSUMERS" Then
		' TODO Sort will not lose it character after filter. This should be above filter
        Call SortColumn(ctx, "ID")
        SondageJoinVertical(ctx, "ID")
        SondageConditionalHorizontalCopy(ctx, "Mobile", "Phone")
    End If

	' TODO Should this be automatic and obtained from ctx?
	oCursor = UsedRangeCursor(ctx.oSheet)

	If reportType = "PENDING" Then
		' If the reportFilter is ONLINE, filter it, else highlight
		' TODO Add this feature to Sondage
		If reportFilter = "ONLINE" Then
			Call FilterColumn(ctx, "Payment Option", "Online Payment", com.sun.star.sheet.FilterOperator.EQUAL)
		Else
			highlightedCount = HighlightRowWithColumn(ctx, _
				"Payment Option", "Online Payment", RGB(255, 255, 0))
		End If

		' Justify Leftmost cells to left and Rightmost cells to right
		bookRange = GetColumnRange(ctx, "Book")
		bookRange.setPropertyValue("HoriJustify", com.sun.star.table.CellHoriJustify.RIGHT)

		FormatRangeAsNumber(oLocale, oDoc.getNumberFormats(), bookRange, "DD/MM")

		tillDate = ComputeOnRange(ctx, "Book", com.sun.star.sheet.GeneralFunction.MAX)
		fromDate = ComputeOnRange(ctx, "Book", com.sun.star.sheet.GeneralFunction.MIN)

		SetupConditionalForHighPriority(ctx.oDoc, oLocale, bookRange,  badStyleName, "><", 1000, tillDate - priorityThreshold)
	ElseIf reportType = "EKYC" Then
		highlightedCount = HighlightRowWithColumn(ctx, _
			"Consumer Type", "PMUY", RGB(175, 255,  175))
	End If

	SondageTransformSheet(ctx, sonConf, reportType, "Group Width")

	If ErrorLocal$ <> "" Then Goto ErrorHandler
	oCursor = UsedRangeCursor(ctx.oSheet)

	If inputType = "PENDING" Then
		if isDBRequired Then
			If Not AssertColumn(dbCtx, "Address") Then GoTo ErrorHandler
		End If
	End If

	Call ShortenDirections(ctx, groupByColumn)
	Dim sSortBy$: sSortBy = SondageGetPropVal(aSettings, "SortBy")
	If sSortBy <> "" Then
		Call SortColumn(ctx, sGroupBy, sSortBy)
	Else
		Call SortColumn(ctx, sGroupBy)
	End If

	If reportType = "PENDING" and isDBRequired Then
		Call ColumnJoin(CHR(10), "ID", ctx, "Name", dbCtx, 	"Address")
	End If

	sTheme = SondageGetPropVal(aSettings , "Theme")
	If Not IsEmpty(sTheme) Then ApplyTheme(ctx.oDoc, sTheme)

	idRange = GetColumnRange(ctx, "ID")
	idRange.setPropertyValue("HoriJustify", com.sun.star.table.CellHoriJustify.LEFT)

	' Setup exportPrefix and sheetName
	tillDateStr = Format(tillDate, "yyyy-mm-dd")
	sheetNameSuffix = " - " & reportType & " " & tillDateStr
	exportDestDir = tillDateStr & " " & reportType

	headerRange = ctx.oSheet.getCellRangeByPosition(0, 0, ctx.endColumn, 0)
	headerRange.CellStyle = "Heading 1"

	pageStyle = ctx.oDoc.StyleFamilies.getByName("PageStyles").getByName("Default")
	pageStyle.setPropertyValue("PrintGrid", True)
	pageStyle.setPropertyValue("CenterHorizontally", True)

	pageStyle.HeaderIsOn = True
	pageStyle.HeaderShared = True
	pageStyle.FirstPageHeaderIsShared = True

	' TODO simplify this logic, recalculate everytime
	If highlightedCount <> 0 Then
		If reportType = "PENDING" Then
			Call SetHeader(pageStyle,  Date() & " | FROM: " & fromDate, ,  "ONLINE: " & CStr(highlightedCount))
		ElseIf reportType ="EKYC" Then
			Call SetHeader(pageStyle, "GENERATED ON: " & Date(), ,  "PMUY: " & CStr(highlightedCount))
		End If
	End if

	pageStyle.setPropertyValue("LeftMargin", 0.2 * 2540)
	pageStyle.setPropertyValue("RightMargin", 0.2 * 2540)

	' Change original sheet name
	ctx.oSheet.Name = "ALL" & sheetNameSuffix

	' Clear subtotals if any before exporting area wise
	If shouldRunSubtotals Then oCursor.removeSubtotals()

	If enableGroupReports Then
		iGroupByColumn =  GetHeaderPosition(ctx, sGroupBy)
		If iGroupByColumn = -1 Then Goto ErrorHandler
		If GenerateIndividualSheets(ctx, sonConf, reportType, sGroupBy, statusBar, False) = False Then
			Goto ErrorHandler
		End If
	End If

	Dim summaryCtx as SondageContext: summaryCtx = ctx
	summaryCtx.oSheet = oDoc.getSheets().getByIndex(1)

	Dim sValidationList$
	If reportType = "PENDING" Then
		sValidationList = pendingRemarksValidateList
	ElseIf reportType = "EKYC" Then
		sValidationList = ekycRemarksList
	End If
	
	If sValidationList <> "" Then
		' FIXME Add this check dynamically from config sheet
		CreateValidationList(ctx, "Remarks", sValidationList)
	End If

	If shouldRunSubtotals Then
		Call RunSubtotals(oCursor, groupByColumn, statusBar)
		Call ReArrangeResultToHeader(summaryCtx)
	End If

	If statusBar Then statusBar.end()

	' Export summary
	If shouldExportPDF Then
		ExportAs(oDoc, ctx.oSheet, exportPrefix, exportDestDir, "pdf")
	End If

	if shouldExportSummaryEditable Then
		ExportAs(oDoc, ctx.oSheet, exportPrefix, exportDestDir, "ods")
	End If

	FinalFallback:
		If Not IsEmpty(organizeInputsFolder) Then
			If Not FileExists(organizeInputsFolder) Then MkDir(organizeInputsFolder)

			Dim sBackupInputFile: sBackupInputFile = organizeInputsFolder & GetPathSeparator()  & tillDateStr & " " & reportType & ".csv"
			If sBackupInputFile <> sInputFile Then
				FileCopy(sInputFile, sBackupInputFile)
			End If
		End If

		If Environ("USERPROFILE") <> "" Then
			' Assume this is windows
			Shell(Environ("COMSPEC"), 1, "/c start "" " & QS(QS(exportPrefix & GetPathSeparator() & exportDestDir)))
		End If
		If isHeadless Then
			' ThisComponent.Close(True) will close all open documents, we don't want that
			ThisComponent.CurrentController.Frame.Close(True)
		End If

	ErrorHandler:
		If statusBar Then statusBar.end()

		' This is the target document, so we close it everytime when not debugging
		If Not IsNull(oDBDoc) and debugInputFile = False Then
			oDoc.unlockControllers()
			oDoc.Close(True)
		End If

		' Only close the DB file, when we are not debugging
		If Not IsNull(oDBDoc) and debugInputFile = False Then
			oDBDoc.unlockControllers()
			oDBDoc.Close(True)
		End If

		If ErrorLocal$ <> "" Then
			MsgBox ErrorLocal$, 16, "FATAL Subfunction Error"
			Exit Sub
		End If

		If Erl <> 0 Then
			MsgBox "Line " & Erl & ": "&  Error$, 16, "FATAL Main Error"
			On Error GoTo 0
			Exit Sub
		End If

		If removeInputFileAfterSuccess Then
			Kill(sInputFile)
		End If
End Sub

Function CopyRange(dstCtx as SondageContext, srcCtx as SondageContext, startRow&, endRow&)
    ' Calculation for selecting the proper range
    ' start                     end
    '1 :                           endColumn          0 4
    'groupByColumn + 1 : endColumn           2  4
    '0 :                           endColumn - 1     4  4

    ' Copy Header
    srcCtx.oSheet.copyRange(dstCtx.oSheet.getCellRangeByName("A1").CellAddress, _
        srcCtx.oSheet.getCellRangeByPosition( _
        srcCtx.startColumn, _
        0, srcCtx.endColumn, 0).RangeAddress)

    ' Copy Contents
    srcCtx.oSheet.copyRange(dstCtx.oSheet.getCellRangeByName("A2").CellAddress, _
        srcCtx.oSheet.getCellRangeByPosition(_
        srcCtx.startColumn, _
        startRow, _
        srcCtx.endColumn, _
        endRow).RangeAddress)
End Function

Function GenerateIndividualSheets(ctx as SondageContext, sonConf as SondageConfiguration, reportType, sGroupByColumn$, statusBar as Variant, Optional sortColumn as Boolean) as Boolean
	' WARNING: This function requires a sorted column, unless specied as False in sortColumn
    ' In that case, the column is assumed sorted
	Dim dstSheet as Variant
	Dim startRow&
	Dim a$, sheetName$
	Dim iRow&, iGroupBy%
    Dim dstCtx as New SondageContext
    GenerateIndividualSheets = False
    
    statusBar.start("Creating " & sGroupByColumn & " Wise", 100)

	iGroupBy = GetHeaderPosition(ctx, sGroupByColumn)
	If iGroupBy <> 0 Then
		ErrorLocal$ = "Cannot generate group reports: '" & sGroupByColumn & "' must be the first column"
		Exit Function
	End If

	ctx.startColumn = 1

	If IsMissing(sortColumn) Then sortColumn = True
	iRow = ctx.startRow
	Do While iRow <= ctx.endRow
		a = ctx.oSheet.getCellByPosition(iGroupBy, iRow).getString()
		If a = "" Then Exit Do
		startRow = iRow

		Do While iRow <= ctx.endRow
			If ctx.oSheet.getCellByPosition(iGroupBy, iRow).getString() <> a Then Exit Do
			iRow = iRow + 1
		Loop

		statusBar.setText("Generating report for " & a)
		statusBar.setValue((iRow / ctx.endRow) * 100)
		sheetName = a & sheetNameSuffix

		' Prepare Destination sheet
		dstSheet = NewSheet(ctx.oDoc, sheetName)
        dstCtx = SondageGetContext(dstSheet)
		dstCtx.endRow = ctx.endRow
		dstCtx.endColumn = ctx.endColumn
        CopyRange(dstCtx, ctx, startRow, iRow - 1)

		' TODO Copy only required cells, instead of copying and deleting for GroupBys
		Dim testAreaColumn: testAreaColumn = GetHeaderPosition(dstCtx, sGroupByColumn)
		if testAreaColumn > 0 Then
			dstSheet.getColumns().removeByIndex(testAreaColumn, 1)
		End If

	    SondageTransformSheet(dstCtx, sonConf, reportType, "Width")

		If shouldExportPDF Then
			if ExportAs(dstCtx.oDoc, dstCtx.oSheet, exportPrefix, exportDestDir, "pdf") = False Then Exit Function
		End If
	Loop
	GenerateIndividualSheets = True
End Function

Function RunSubtotals(oCursor, iColumn, Optional statusBar as Variant)
    If Not IsMissing(statusBar) Then statusBar.setText("Running subtotals")
    Dim oSubtotalDesc : oSubtotalDesc = oCursor.createSubTotalDescriptor(true)
    Dim oSubtotalColumn(0) as new com.sun.star.sheet.SubTotalColumn

    With oSubtotalColumn(0)
        .Column = iColumn
        .Function = com.sun.star.sheet.GeneralFunction.COUNT
    End With
    oSubtotalDesc.addNew(oSubtotalColumn, iColumn)
    oCursor.applySubtotals(oSubtotalDesc, true)
End Function

Sub SubstituteContent(oDoc, oShape, oProduct)
	' TODO Maybe change from If Not to If and show error?
	If oShape.getName() = "" Then
		Exit Sub
	End If
	If oShape.getName() = "StovePrice" Then
		If oProduct.Price <> 0 Then
		oShape.setString(CURRENCY_UNIT & CStr(oProduct.Price))
		End If
	ElseIf oShape.getName() = "ProductBlurb" Then
		If oProduct.Description <> "" Then
			oShape.setString(oProduct.Description)
		End If
	ElseIf oShape.getName() = "ProductTitle" Then
		If IsEmpty(oProduct.Title) Then
			oShape.setString(oProduct.Title)
		End If
	End If
End Sub

Function GetFirstOpenDocument(docType as String)
	Dim oComponents: oComponents = StarDesktop.getComponents()
	Dim oDoc
	Dim oDocs: oDocs = oComponents.createEnumeration()
	Do While oDocs.hasMoreElements()
		oDoc = oDocs.nextElement()
		If  oDoc.supportsService(docType) Then
			GetFirstOpenDocument = oDoc
			Exit Function
		End If
	Loop
End Function

Sub Dialog1Show
    With GlobalScope.BasicLibraries
       If Not .IsLibraryLoaded("Tools") Then .LoadLibrary("Tools")
    End With
    Dim oAddBtn
    Dim oDialog1
    Dim oColorTbl, oHeaders, oColumn1, oColumn2, oColumn3, oComboBox, oDataModel
    oDialog1 = Tools.ModuleControls.LoadDialog("Standard", "Dialog1")
    oAddBtn = oDialog1.getControl("AddBtn").getModel()
    oColorTbl = oDialog1.getControl("ColorTable").getModel()
    oColorTbl.Width = 150 ' TODO get width value from column

	oColumn1 = createUnoService( "com.sun.star.awt.grid.GridColumn")
    oColumn2 = createUnoService( "com.sun.star.awt.grid.GridColumn")
    oColumn3 = createUnoService( "com.sun.star.awt.grid.GridColumn")

	oColumn1.Title = "Condition"
	oColumn1.MaxWidth = 30
	oColumn2.Title = "Value"
	oColumn2.MaxWidth = 30
	oColumn3.Title = "Color"

	'	Print oColumn3.dbg_properties()
    oHeaders = createUnoService("com.sun.star.awt.grid.DefaultGridColumnModel")
    oDataModel = createUnoService( "com.sun.star.awt.grid.DefaultGridDataModel")

    oHeaders.addColumn(oColumn1)
    oHeaders.addColumn(oColumn2)
    oHeaders.addColumn(oColumn3)
    
    oColorTbl.GridDataModel = oDataModel
	
    oColorTbl.ColumnModel = oHeaders
    oDataModel.addRow("1", Array(">", "45", "#ff0000"))
    oDialog1.Execute()
End Sub

Sub SetCustomBadStyle(oDoc, oLocale, styleName as String)
	Dim oCellStyles
	Dim oStyle
	Dim formatNum%
	oCellStyles = oDoc.StyleFamilies("CellStyles")
	If oCellStyles.hasByName(styleName) Then
		oCellStyles.removeByName(styleName)
	End If
	oStyle = oDoc.createInstance("com.sun.star.style.CellStyle")
	oCellStyles.insertByName(styleName, oStyle)
	oStyle = oCellStyles.getByName(styleName)
	oStyle.CellBackColor = RGB(255, 0, 0)
	formatNum = GetNumberFormatNumber(oLocale, oDoc.getNumberFormats(), "DD/MM")
	If formatNum = -1 Then
		ErrorLocal$ = "WARNING: Cannot add '" & formatStr & "' as NumberFormat"
		Exit Sub
	End If
	oStyle.NumberFormat = formatNum
End Sub

Sub SetupConditionalForHighPriority(oDoc, oLocale, oRange, styleName$, _
		opCond$, formula1 as Variant, Optional formula2 as Variant)
		
	' TODO Rework this function to automagically handle dates
	Dim oConFormat
	Dim oCondition(3) as new com.sun.star.beans.PropertyValue

	'BasicLibraries.LoadLibrary("Sondage")

	' FIXME This may very well crash on some operations, I have no idea, because
	' I have not tested it
	If IsMissing(formula2) Then formula2 = "0"
	
	If TypeName(formula1) = "Date" Then
		formula1 = CStr(CLng(formula1))
	End If
	
	If TypeName(formula2) = "Date" Then
		formula2 = CStr(CLng(formula2))
	End If

	With oCondition(0)
		.Name = "Operator"
		.Value = SondageGetCondTypeFromString(opCond)
	End With
	With oCondition(1)
		.Name = "Formula1" 
		.Value =  formula1
	End With
	With oCondition(2)
		.Name = "Formula2"
		.Value = formula2
	End With
    With oCondition(3)
    	.Name = "StyleName"
    	.Value = styleName
    End With
    
	oConFormat = oRange.ConditionalFormat
	oConFormat.clear()
	oConFormat.addNew(oCondition)
	oRange.ConditionalFormat = oConFormat
End Sub

Sub ShowFilterOptions()
	Dim args(), i%
	args() = StarDesktop.CurrentComponent.getArgs()
	For i = 0 to uBound(Args())
	   If args(i).Name = "FilterOptions" then inputbox args(i).Name,"",cStr(args(i).value)
	Next
End Sub
