Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging


Public Class FrmNewTable
    Private _logConfig As LogConfig
    Private _logger As Logger
    Private _db As Firebird

    Public Sub New(LogConfig As LogConfig)
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        _logConfig = LogConfig
        _logger = _logConfig.GetLogger()
    End Sub

    Private Sub FrmNewTable_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            _db = New Firebird(_logConfig, My.Settings.fbDatasource, My.Settings.fbDatabaseLocation, My.Settings.fbUser, My.Settings.fbPassword)
        Catch ex As Exception
            MsgBox("Connection to DB failed!", MsgBoxStyle.Critical)
            _logger.Error(ex)
        End Try
    End Sub

    Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
        Dim oTableName As String = txtTablename.Text

        If oTableName.Trim() = String.Empty Then
            MsgBox("Table name cannot be empty!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If

        Dim oExistingTableId = _db.GetScalarValue($"SELECT GUID FROM TBEDM_TABLE WHERE DESCRIPTION = '{oTableName}'")

        If oExistingTableId IsNot Nothing Then
            MsgBox("Table already exists!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If

        Dim oResult = _db.GetScalarValue($"SELECT FNCREATE_TABLE('{oTableName}','{Environment.UserName}') FROM rdb$database;")

        If oResult >= 0 Then
            Close()
        Else
            MsgBox("An error occurred while creating the table. Check the log", MsgBoxStyle.Critical)
        End If
    End Sub
End Class