Imports System.Reflection
Imports System.Windows.Forms
Imports DigitalData.Modules.Logging

Namespace Base
    Public Class BaseErrorHandler
        Private _LogConfig As LogConfig
        Private _Logger As Logger
        Private _Form As Form

        Public Sub New(LogConfig As LogConfig, Logger As Logger, Form As Form)
            _LogConfig = LogConfig
            _Logger = Logger
            _Form = Form
        End Sub

        Public Sub ShowErrorMessage(Exception As Exception, Origin As String)
            Dim oMessage = GetMessage(Exception, Origin)
            ShowErrorMessage(Exception, Origin, oMessage)
        End Sub

        Public Sub ShowErrorMessage(Exception As Exception, Origin As String, Message As String)
            _Logger.Error(Exception)
            MessageBox.Show(Message, _Form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Sub

        Public Sub ShowErrorMessage(Text As String)
            _Logger.Info(Text)
            MessageBox.Show(Text, _Form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Sub

        Public Sub ShowWarningMessage(Text As String)
            _Logger.Info(Text)
            MessageBox.Show(Text, _Form.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Sub

        Public Sub ShowInfoMessage(Text As String)
            _Logger.Info(Text)
            MessageBox.Show(Text, _Form.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Sub

        Private Function GetMessage(Exception As Exception, Origin As String) As String
            Dim oMessage As String = String.Empty

            If TypeOf Exception Is SqlClient.SqlException Then
                Dim oNumber As Integer = DirectCast(Exception, SqlClient.SqlException).Number
                Select Case oNumber
                    Case 2627
                        oMessage = "Es wurde ein Doppelter Wert in eine Spalte eingetragen, die einzigartig sein muss."
                    Case Else
                        oMessage = Exception.Message
                End Select
            ElseIf TypeOf Exception Is NoNullAllowedException Then
                oMessage = "Einige benötigte Felder wurde nicht ausgefüllt."
            Else
                oMessage = $"An unhandled exception occurred in {Origin}: " & vbNewLine &
                    Exception.Message & vbNewLine & vbNewLine &
                    "More information can be found in the Application Log."
            End If

            If _LogConfig.Debug Then
                oMessage &= vbNewLine & vbNewLine & "=== Debug Information ==="
                oMessage &= vbNewLine & vbNewLine & "Stacktrace:"
                oMessage &= vbNewLine & Exception.StackTrace
            End If

            Return oMessage
        End Function
    End Class

End Namespace
