Imports System.ComponentModel
Imports System.Threading
Public NotInheritable Class frmSplash
    Private InitSteps As Integer = 4
    Private Worker As New BackgroundWorker()
    Private MainForm As Form

    Private Sub frmSplash_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
        If e.KeyCode = Keys.Escape Then
            ESC_Hidden = True
        End If
    End Sub

    Private Sub frmSplash_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Version.Text = String.Format("Version {0}", My.Application.Info.Version.ToString)
        Copyright.Text = String.Format("{0} {1}", My.Application.Info.Copyright, My.Application.Info.CompanyName)

        BringToFront()
        InitProgram()
    End Sub

    Private Sub InitProgram()
        Worker.WorkerReportsProgress = True
        AddHandler Worker.DoWork, AddressOf bw_DoWork
        AddHandler Worker.ProgressChanged, AddressOf bw_ProgressChanged
        AddHandler Worker.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted

        Worker.RunWorkerAsync()
    End Sub

    Private Function CalcProgress(_step As Integer)
        Return _step * (100 / InitSteps)
    End Function

    Private Sub bw_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs)
        Try
            Dim Init = New ClassInit()
            Worker.ReportProgress(CalcProgress(1), "Initializing Logger")
            Init.InitLogger()
            Thread.Sleep(200)

            Worker.ReportProgress(CalcProgress(2), "Initializing Base Config")
            Init.InitBasics()
            Thread.Sleep(200)

            Worker.ReportProgress(CalcProgress(3), "Initializing Database")
            If Init.InitDatabase_New() = True Then
                Thread.Sleep(200)

                Worker.ReportProgress(CalcProgress(4), "Initializing User-Configuration")
                If ClassInit.InitUserLogin = False Then
                    If ERROR_INIT = "" Then
                        ERROR_INIT = "INVALID USER"
                    End If
                End If

                Thread.Sleep(200)

            Else
                ERROR_INIT = "DATABASE"
            End If

        Catch ex As Exception
            MsgBox("Unexpected Error in bw_DoWork: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub bw_ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
        pbStatus.Value = e.ProgressPercentage
        lblStatus.Text = e.UserState.ToString()
    End Sub

    Private Sub bw_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
        ' Bei Fehler MsgBox anzeigen und Programm beenden
        If e.Error IsNot Nothing Then
            MsgBox(e.Error.Message, MsgBoxStyle.Critical, "Unexpected Error in frmSplash")
            Application.Exit()
        End If

        ' Wenn kein Fehler, Splashscreen schließen
        Close()
    End Sub
End Class
