Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging
Imports System.IO

Public Class FrmMain
    Private _selectedTable As Integer
    Private _selectedTableName As String

    Private _logger As Logger
    Private _logConfig As LogConfig
    Private _firebird As Firebird

    Private Sub CreateTableNodesFromDatatable(DataTable As DataTable, DatabaseName As String)
        treeViewMain.Nodes.Clear()

        ' Node der Datenbank erstellen
        Dim oDbNode As New TreeNode With {
            .Text = DatabaseName,
            .Name = "DATABASE"
        }

        ' Übernode für Tabellen erstellen
        Dim oTablesNode As New TreeNode With {
            .Text = "Tabellen",
            .Name = "TABLES"
        }

        ' Nodes für Tabellen erstellen
        Dim oTableNodeList As New List(Of TreeNode)

        For Each row As DataRow In DataTable.Rows
            Dim oNode As New TreeNode With {
                .Text = row.Item("TABLE"),
                .Name = row.Item("TABLE"),
                .Tag = row.Item("TABLE_ID")
            }

            oTableNodeList.Add(oNode)
        Next

        ' Nodes zusammenfügen
        oTablesNode.Nodes.AddRange(oTableNodeList.ToArray)
        oDbNode.Nodes.Add(oTablesNode)

        ' Nodes einhängen
        treeViewMain.Nodes.Add(oDbNode)
        treeViewMain.ExpandAll()
    End Sub

    Private Function LoadTables()
        Return _firebird.GetDatatable("SELECT DISTINCT T.TABLE_ID,T.""TABLE"" from VWEDM_TABLE_COLUMN T")
    End Function

    Private Function DatabaseSettingsExist()
        Return My.Settings.fbDatabaseLocation <> String.Empty And My.Settings.fbDatasource <> String.Empty And My.Settings.fbUser <> String.Empty And My.Settings.fbPassword <> String.Empty
    End Function

    Private Sub Init()
        Try
            _firebird = New Firebird(_logConfig, My.Settings.fbDatasource, My.Settings.fbDatabaseLocation, My.Settings.fbUser, My.Settings.fbPassword)

            ' Get info about the logged in user
            'CurrentUser = New ClassCurrentUser(DBFirebird)

            Dim dt As DataTable = LoadTables()
            CreateTableNodesFromDatatable(dt, _firebird.DatabaseName)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub FrmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
        _logConfig = New LogConfig(LogConfig.PathType.CurrentDirectory)
        _logger = _logConfig.GetLogger()  '_logConfig.LogFactory.GetCurrentClassLogger(GetType(Logger))

        _logger.NewBlock("STARTUP")
        _logger.Info("INFO")
        _logger.Warn("WARN")
        _logger.NewBlock("ERROR")


        Try
            Throw New Exception("ERROR")
        Catch ex As Exception
            _logger.Error(ex)
        End Try

        ' Check for existing database credentials
        While Not DatabaseSettingsExist()
            Dim form As New FrmConnection With {
                .LogConfig = _logConfig
            }
            Dim result As DialogResult = form.ShowDialog()

            If result = DialogResult.OK Then
                Exit While
            End If
        End While

        Init()
    End Sub

    Private Sub TreeViewMain_NodeMouseClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles treeViewMain.NodeMouseClick
        If e.Button = MouseButtons.Right Then
            _selectedTable = -1
            _selectedTableName = Nothing

            ' Wenn kein Node geklickt wurde, aussteigen
            If e.Node Is Nothing OrElse e.Node.Parent Is Nothing Then
                Exit Sub
            End If

            Dim parentName As String = e.Node.Parent.Name

            ' Das Kontextmenü für den angeklickten Node öffnen
            Select Case parentName
                Case "TABLES"
                    _selectedTable = e.Node.Tag
                    _selectedTableName = e.Node.Name
                    contextMenuTable.Show(MousePosition)
                Case "DATABASE"
                    contextMenuDatabase.Show(MousePosition)
            End Select

            treeViewMain.SelectedNode = e.Node
        End If
    End Sub


    Private Sub TabelleBearbeitenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles TabelleBearbeitenToolStripMenuItem.Click
        Dim oDataTable = New DataTable()
        Dim oConnection = _firebird.GetConnection()
        Dim oDataAdapter = New FirebirdSql.Data.FirebirdClient.FbDataAdapter($"SELECT * FROM VWEDM_TABLE_COLUMN WHERE TABLE_ID = {_selectedTable}", oConnection)

        Try
            oDataAdapter.Fill(oDataTable)
            gridControlTableProperties.DataSource = oDataTable
        Catch ex As Exception
            _logger.Error(ex)
            MsgBox($"Error while loading columns for table {_selectedTable}")
        Finally
            oConnection.Close()
        End Try

        oDataTable = New DataTable()
        oConnection = _firebird.GetConnection()
        oDataAdapter = New FirebirdSql.Data.FirebirdClient.FbDataAdapter($"SELECT * FROM VW_{_selectedTableName}", oConnection)

        Try
            oDataAdapter.Fill(oDataTable)
            gridControlTableData.DataSource = oDataTable
        Catch ex As Exception
            _logger.Error(ex)
            MsgBox($"Error while loading data for table {_selectedTable}")
        Finally
            oConnection.Close()
        End Try

        'Dim dt As DataTable = _firebird.GetDatatable($"SELECT * FROM VWEDM_TABLE_COLUMN WHERE TABLE_ID = {_selectedTable}")
        'gridControlTableProperties.DataSource = dt
    End Sub

    Private Sub NeueTabelleToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NeueTabelleToolStripMenuItem.Click
        Dim oForm As New FrmNewTable(_logConfig)
        oForm.ShowDialog()

        Dim oTables As DataTable = LoadTables()
        CreateTableNodesFromDatatable(oTables, _firebird.DatabaseName)
    End Sub
End Class
