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

Global Const GVT_INSERT_PHONEBOOK_QUERY = "INSERT INTO `phonbook`(num,nam,adrs,stat,cty,zipc,eml,cid,num1,oth1,oth2,oth3,oth4,oth5,oth6,oth7,oth8,oth9,oth10) VALUES"
Global Const GVT_INSERT_BROADCAST_QUERY = "INSERT INTO `fctnum`(usr,nam,num,stt,cty,callon,stts,fedbck,oth1,oth2,oth3,oth4,oth5,oth6,oth7,oth8,oth9,oth10,dispo,clientID) VALUES"
Function QS(sQueryValue) as String
	QS = CHR(34) & sQueryValue & CHR(34)
End Function

Function GenerateEmptyDoubleQuotes(iEmptyCount as Integer) as String
	Dim i%
	Dim sQuery as String
	For i = 1 To iEmptyCount
		sQuery =  sQuery & "," & QS("")
	Next i
	GenerateEmptyDoubleQuotes = sQuery
End Function

Function ConstructSQLValues(sQueryValues, iEmptyAppend as Integer) as String
	Dim i
	Dim sQuery as String
	sQuery = "("
	For i = LBound(sQueryValues) To UBound(sQueryValues)
		' TODO Simplif sQuery assignment
		If TypeName(sQueryValues(i)) = "String" Then
			sQuery = sQuery & IIf(sQueryValues(i)="", QS(""), QS(sQueryValues(i)))
		Else
			sQuery = sQuery &  sQueryValues(i)
		End If
		If i <> UBound(sQueryValues) Then sQuery = sQuery & ","
	Next i

	sQuery =  sQuery & GenerateEmptyDoubleQuotes(iEmptyAppend)
	sQuery = sQuery & ")"
	ConstructSQLValues = sQuery
End Function

Sub PopulateConsumerDetails(dbFilePath, ctx as Object)
	' Connect using JDBC to Advance.mdb
	' INSERT INTO phonbook(id, name, mobile) values (...)
	Dim oManager, oCon, oStatement, oPrepStatement, oResult
	Dim oParms(2) As New com.sun.star.beans.PropertyValue
	Dim sURL as String, sSQL as String
	
	' TODO Remove this, and use ctx directly to avoid confusion
	Dim oSheet: oSheet = ctx.oSheet
	
	' TODO Save memory and improve speed by switching to jackhess API
	sURL = "jdbc:ucanaccess://" & dbFilePath & GetPathSeparator() & "Advance.mdb"
	oManager = CreateUnoService("com.sun.star.sdbc.DriverManager")
	oParms(0).Name = "user"
	oParms(0).Value = ""
	oParms(1).Name = "password"
	oParms(1).Value = ""
	oParms(2).Name = "JavaDriverClass"
	oParms(2).Value = "net.ucanaccess.jdbc.UcanloadDriver"
	oCon = oManager.GetConnectionWithInfo(sURL, oParms())
	oStatement = oCon.CreateStatement()

	Dim iIDCol%, iEmailCol%, iNameCol%, iAddressCol%, iPincodeCol%, iMobileCol%, iPhoneCol%
	iIDCol = GetHeaderPosition(ctx, "ID")
	iEmailCol = GetHeaderPosition(ctx, "Email")
	iNameCol = GetHeaderPosition(ctx, "Name")
	iAddressCol = GetHeaderPosition(ctx, "Address")
	iPincodeCol = GetHeaderPosition(ctx, "Pin Code")
	iMobileCol = GetHeaderPosition(ctx, "Mobile")
	iPhoneCol = GetHeaderPosition(ctx, "Phone")

	
	Dim i as Long
	Dim id as Double
	Dim sIdq as String
	' Indian phone numbers are 10 digits, Doucbe can hold ~15 digits in LO Basic
	Dim num as Double
	Dim num1 as Double
	Dim zipc as Double

	Dim adrs as String
	Dim nam as String
	Dim eml as String
	
	'On Error Goto SQLCmdErrorHandle
	For i = 1 To oSheet.getRows().getCount() - 1
		id = CLng(oSheet.getCellByPosition(iIDCol, i).Value)
		sIdq = QS(CStr(id))
		nam = oSheet.getCellByPosition(iNameCol, i).String
		'eml = oSheet.getCellByPosition(iEmailCol, i).String
		adrs = oSheet.getCellByPosition(iAddressCol, i).String
		'zipc = oSheet.getCellByPosition(iPincodeCol, i).Value
		num = oSheet.getCellByPosition(iMobileCol, i).Value
		'num1 = oSheet.getCellByPosition(iPhoneCol, i).Value

		' Check if id exists in phonbook
		sSQL = "SELECT * FROM `phonbook` WHERE cid=" & sIdq
		oResult = oStatement.executeQuery(sSQL)
		If oResult.next() Then
			' id exists in phonbook, we should do an update
			sSQL = "UPDATE `phonbook` SET " & _
				"num=?, nam=?, adrs=?,zipc=?,eml=?,num1=?" & _
				" WHERE cid=" & sIdq
			oPrepStatement = oCon.prepareStatement(sSQL)
				With oPrepStatement
					.setString(1, num)
					.setString(2, nam)
					.setString(3, adrs)
					.setString(4, zipc)
					.setString(5, eml)
					.setString(6, num1)
				End With
			
			'oResult = oStatement.prepareStatement(sSQL)
			oPrepStatement.executeUpdate()
		Else
			' GVT Advance has additonal fields which we cannot ignore during an insert(results in a NULL CONSTRAINT violation)
			' So we are expanding `""` 10 times to make UCanaccess happy
			' This can be grarcefully handled by using Jackcess API
			sSQL =  GVT_INSERT_PHONEBOOK_QUERY & _
				"(?,?,?,?,?,?,?,?,?" & _
				GenerateEmptyDoubleQuotes(10) & ")"
				'ConstructSQLValues(Array(num, nam, adrs, stateName, cityName, zipc, eml, id, num1), 10)

			'https://stackoverflow.com/a/35844168/4816020
			'oStatement.executeUpdate(sSQL)
			oPrepStatement = oCon.prepareStatement(sSQL)
			With oPrepStatement
				.setString(1, num)
				.setString(2, nam)
				.setString(3, adrs)
				.setString(4, stateName)
				.setString(5, cityName)
				.setString(6, zipc)
				.setString(7, eml)
				.setString(8, id)
				.setString(9, num1)
			End With
			oPrepStatement.executeUpdate()
		End If
	Next i
	
	oCon.Close()
	Exit Sub
	SQLCmdErrorHandle:
		ErrorLocal$ = "SQL Update error: Error while executing: " & sSQL & CHR(10) & Erl() & ": " & Error()
		Reset
		oCon.Close()
End Sub

Sub ReducedPopulateConsumerDetails(dbFilePath, oSheet as Object)
	' Connect using JDBC to Advance.mdb
	' INSERT INTO phonbook(id, name, mobile) values (...)
	Dim oManager, oCon
	Dim oCheckStatement, oInsertStatement, oUpdateStatement, oResult
	Dim oParms(2) As New com.sun.star.beans.PropertyValue
	Dim sURL as String, sSQL as String
	Dim oUsedRange: oUsedRange = UsedRangeCursor(oSheet)
	
	Dim endRow&: endRow = oUsedRange.RangeAddress.EndRow
	
	' TODO Save memory and improve speed by switching to jackhess API
	sURL = "jdbc:ucanaccess://" & dbFilePath & GetPathSeparator() & "Advance.mdb"
	oManager = CreateUnoService("com.sun.star.sdbc.DriverManager")
	oParms(0).Name = "user"
	oParms(0).Value = ""
	oParms(1).Name = "password"
	oParms(1).Value = ""
	oParms(2).Name = "JavaDriverClass"
	oParms(2).Value = "net.ucanaccess.jdbc.UcanloadDriver"
	oCon = oManager.GetConnectionWithInfo(sURL, oParms())	
	
	Dim endColumn%, iIDCol%, iNameCol%, iAddressCol%, iMobileCol%
	endColumn = UsedRangeCursor(oSheet).RangeAddress.EndColumn
	iIDCol = GetHeaderPosition(oSheet, endColumn, "ID")
	iNameCol = GetHeaderPosition(oSheet, endColumn, "Name")
	iAddressCol = GetHeaderPosition(oSheet, endColumn, "Address")
	iMobileCol = GetHeaderPosition(oSheet, endColumn, "Mobile")
	
	Dim i as Long
	Dim sIdq as String
	' Indian phone numbers are 10 digits, Doucbe can hold ~15 digits in LO Basic
	Dim id as Double
	Dim nam as String
	Dim adrs as String
	Dim num as Double
	
	oCheckStatement = oCon.createStatement()
	'oResult = oCheckStatement.executeQuery("DELETE FROM `fctnum`")
	'oResult = oCheckStatement.executeQuery("UPDATE `fctnum` SET usr=" & QS("Somen"))

	'oCheckStatement = oCon.prepareStatement("SELECT * FROM `phonbook` WHERE cid=?")
	Dim sCheck$: sCheck = "SELECT * FROM `fctnum` WHERE clientID="
	oUpdateStatement = oCon.prepareStatement("UPDATE `fctnum` SET nam=?, num=? WHERE clientID=?")

	sSQL = GVT_INSERT_BROADCAST_QUERY & _
			"(" & QS("admin") & ",?,?," & _
			QS(stateName) & "," & _
			QS(cityName) & "," & _
			QS("01-Jan-01") & _
			GenerateEmptyDoubleQuotes(13) & "," & _
			"?)"
	oInsertStatement = oCon.prepareStatement(sSQL)
	'On Error Goto SQLCmdErrorHandle
	For i = 1 To endRow
		id = CLng(oSheet.getCellByPosition(iIDCol, i).Value)
		nam = oSheet.getCellByPosition(iNameCol, i).String
		'adrs = oSheet.getCellByPosition(iAddressCol, i).String
		num = oSheet.getCellByPosition(iMobileCol, i).Value
		
		sIdq = QS(CStr(id))
		sSQL = sCheck & sIdq
		' Check if id exists in phonbook
		'oCheckStatement.setString(1, sIdq)
		oResult = oCheckStatement.executeQuery(sSQL)
		If oResult.next() Then
				With oUpdateStatement
					.setString(1, nam)
					.setString(2, num)
					'.setString(3, adrs)
					.setString(3, id)
					'.setString(4, zipc)
					'.setString(5, eml)
					'.setString(6, num1)
				End With
			
			'oResult = oStatement.prepareStatement(sSQL)
			oUpdateStatement.executeUpdate()
		Else
			' GVT Advance has additonal fields which we cannot ignore during an insert(results in a NULL CONSTRAINT violation)
			' So we are expanding `""` 10 times to make UCanaccess happy
			' This can be grarcefully handled by using Jackcess API

			'https://stackoverflow.com/a/35844168/4816020
			'oStatement.executeUpdate(sSQL)
			With oInsertStatement
				.setString(1, nam)
				.setString(2, num)
				'.setString(3, adrs)
				'.setString(4, stateName)
				'.setString(5, cityName)
				'.setString(6, zipc)
				'.setString(7, eml)
				.setString(3, id)
				'.setString(9, num1)
			End With
			oInsertStatement.executeUpdate()
		End If
	Next i
	
	oCon.Close()
	Exit Sub
	SQLCmdErrorHandle:
		ErrorLocal$ = "SQL Update error: Error while executing: " & sSQL & CHR(10) & Erl() & ": " & Error()
		Reset
		oCon.Close()
End Sub
