Imports System.Data.SqlClient
Imports Oracle.ManagedDataAccess.Client
Imports DigitalData.Modules.Logging
Public Class clsDatabase
    Private Shared MSSQL_inited As Boolean = False
    Dim Logger As Logger
    Sub New(MyLogger As LogConfig)
        Logger = MyLogger.GetLogger()
    End Sub
    Public Function Init(CONSTRING As String, pSaveCS As Boolean)
        Try
            Dim SQLconnect As New SqlClient.SqlConnection
            SQLconnect.ConnectionString = CONSTRING
            SQLconnect.Open()
            SQLconnect.Close()
            If pSaveCS = True Then
                clsCURRENT.SQLSERVER_CS = CONSTRING

            End If
            MSSQL_inited = True
            Return True
        Catch ex As Exception
            Logger.Error(ex, $"CONSTRING: {CONSTRING}")
            'clsLogger.Add("Error in DatabaseInit: " & ex.Message, True)
            Return False
        End Try
    End Function

    Public Function MSSQL_CS_Test(CONSTRING As String)
        Try

            ' die nötigen Variablen definieren
            Dim Connection As SqlConnection = Nothing


            ' Verbindung zur Datenbank aufbauen
            Try
                Connection = New SqlConnection(CONSTRING)
                Connection.Open()
            Catch ex As Exception
                Logger.Error(ex)
                'clsLogger.Add(ex.Message, True, "clsDatatabase.MSSQL_CS_Test(OpenConnection)")
                Return False
            End Try
            Connection.Close()
            Return True

        Catch ex As Exception
            Logger.Error(ex)
            ' an dieser Stelle sollte jeder unvorhergesehene Fehler der Funktion abgefangen werden
            'clsLogger.Add("UNEXPECTED ERROR: " & ex.Message, True, "clsDatatabase.MSSQL_CS_Test")
            Return False
        End Try

    End Function
    Public Function ExecuteonMSSQL(ConString As String, ByVal sqlcommand As String)
        Try
            Logger.Debug("sqlcommand: " & sqlcommand)
            If MSSQL_inited = False Then Return False
            ' die nötigen Variablen definieren
            Dim Connection As SqlConnection = Nothing
            ' Dim ConnectionString As SqlConnectionStringBuilder = Nothing
            Dim Command As SqlCommand = Nothing
            Dim DataAdapter As SqlDataAdapter = Nothing

            '' ConnectionString aufbauen (aus Settings auslesen)
            'ConnectionString = New SqlConnectionStringBuilder()
            'ConnectionString.DataSource = datasource
            'ConnectionString.UserID = User
            'ConnectionString.Password = pw
            'ConnectionString.InitialCatalog = init_Cata



            ' Verbindung zur Datenbank aufbauen
            Try
                Connection = New SqlConnection(ConString)
                Connection.Open()
            Catch ex As Exception
                Logger.Error(ex)
                'clsLogger.Add(ex.Message, True, "clsDatatabase.ExecuteonMSSQL(OpenConnection)")
                Return False
            End Try


            ' SQL-Abfrage definieren
            Try
                Command = New SqlCommand(sqlcommand, Connection)
            Catch ex As Exception
                Logger.Error(ex)
                'clsLogger.Add(ex.Message, True, "clsDatatabase.ExecuteonMSSQL(DefineCommand)")
                Return False
                Connection.Close()
            End Try

            ' *** Ausführen des Command ***
            If Command IsNot Nothing Then

                Try
                    Command.ExecuteNonQuery()
                    ' DB-Connection schliessen
                    Connection.Close()
                    Return True
                Catch ex As Exception
                    Logger.Error(ex)
                    ' bei einem Fehler einen Eintrag in der Logdatei erzeugen
                    'clsLogger.Add(ex.Message, True, "clsDatatabase.ExecuteonMSSQL(ExecuteCommand)")
                    Return False
                    Connection.Close()
                End Try
            Else
                ' kann eintreten, wenn entweder die SQL-Anweisung falsch ist oder wenn die DataConnection nicht richtig aufgebaut werden konnte
                ' Eintrag in Logdatei machen
                Logger.Info("Could not create COMMAND")
                ' clsLogger.Add("Could not create COMMAND", True, "clsDatatabase.ExecuteonMSSQL")
                Return False
                Connection.Close()
            End If
        Catch ex As Exception
            Logger.Error(ex)
            ' an dieser Stelle sollte jeder unvorhergesehene Fehler der Funktion abgefangen werden
            'clsLogger.Add("UNEXPECTED ERROR: " & ex.Message, True, "clsDatatabase.ExecuteonMSSQL")
            Return False
        End Try

    End Function


    Public Function Return_Datatable(Select_anweisung As String, Optional pSQLConnection As String = "")
        Try
            Logger.Debug("Select_anweisung: " & Select_anweisung)
            If MSSQL_inited = False Then Return Nothing
            Dim SQLconnect As New SqlClient.SqlConnection
            Dim SQLcommand As SqlClient.SqlCommand

            If pSQLConnection <> "" Then
                SQLconnect.ConnectionString = pSQLConnection
            Else
                SQLconnect.ConnectionString = clsCURRENT.SQLSERVER_CS
            End If

            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            SQLcommand.CommandText = Select_anweisung
            SQLcommand.CommandTimeout = 180
            Dim adapter1 As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(SQLcommand)
            Dim dt As DataTable = New DataTable()

            adapter1.Fill(dt)
            SQLconnect.Close()

            Return dt
        Catch ex As Exception
            Logger.Error(ex, $"SQL: {Select_anweisung}")
            'clsLogger.Add("Error in Return_Datatable: " & ex.Message, True)
            'clsLogger.Add(">> SQL: " & Select_anweisung, False)

            Return Nothing
        End Try
    End Function
    Public Function Execute_non_Query(ExecuteCMD As String, Optional pSQLConnection As String = "")
        If MSSQL_inited = False Then Return False
        Dim oSQLCON As String
        Try
            Logger.Debug("ExecuteCMD: " & ExecuteCMD)
            Dim SQLconnect As New SqlClient.SqlConnection
            Dim SQLcommand As SqlClient.SqlCommand

            If pSQLConnection <> "" Then
                SQLconnect.ConnectionString = pSQLConnection
                oSQLCON = pSQLConnection
            Else
                SQLconnect.ConnectionString = clsCURRENT.SQLSERVER_CS
                oSQLCON = clsCURRENT.SQLSERVER_CS
            End If

            SQLconnect.ConnectionString = oSQLCON

            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            'Update Last Created Record in Foo
            SQLcommand.CommandText = ExecuteCMD
            SQLcommand.CommandTimeout = 120
            SQLcommand.ExecuteNonQuery()
            SQLcommand.Dispose()
            SQLconnect.Close()



            Return True
        Catch ex As Exception
            Dim msg = $"Unexpected error in Execute_non_Query: SQL: {ExecuteCMD}, oSQLCON: {oSQLCON}"
            Logger.Error(ex)
            Logger.Debug(msg)
            Logger.Info(msg)
            'clsLogger.Add("Error in Execute_non_Query: " & ex.Message, True)
            'clsLogger.Add("SQL: " & ExecuteCMD, False)

            Return False
        End Try
    End Function

    Public Function Execute_Scalar(cmdscalar As String, Optional pSQLConnection As String = "")
        If MSSQL_inited = False Then Return Nothing
        Dim result
        Try
            Logger.Debug("cmdscalar: " & cmdscalar)

            Dim SQLconnect As New SqlClient.SqlConnection
            Dim SQLcommand As SqlClient.SqlCommand

            If pSQLConnection <> "" Then
                SQLconnect.ConnectionString = pSQLConnection
            Else
                SQLconnect.ConnectionString = clsCURRENT.SQLSERVER_CS
            End If


            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            'Update Last Created Record in Foo
            SQLcommand.CommandText = cmdscalar
            SQLcommand.CommandTimeout = 120
            result = SQLcommand.ExecuteScalar()
            SQLcommand.Dispose()
            SQLconnect.Close()


            Return result
        Catch ex As Exception
            Logger.Error(ex, $"SQL: {cmdscalar}")
            'clsLogger.Add("Error in Execute_Scalar: " & ex.Message, True)
            'clsLogger.Add("SQL: " & cmdscalar, False)
            Return Nothing
        End Try
    End Function
End Class
