Imports System.IO.Path
Imports System.Runtime
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.EDMI.API
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Logging.LogConfig
Imports Microsoft.VisualBasic.ApplicationServices

Namespace My
    ' Für MyApplication sind folgende Ereignisse verfügbar:
    ' Startup: Wird beim Starten der Anwendung noch vor dem Erstellen des Startformulars ausgelöst.
    ' Shutdown: Wird nach dem Schließen aller Anwendungsformulare ausgelöst.  Dieses Ereignis wird nicht ausgelöst, wenn die Anwendung mit einem Fehler beendet wird.
    ' UnhandledException: Wird bei einem Ausnahmefehler ausgelöst.
    ' StartupNextInstance: Wird beim Starten einer Einzelinstanzanwendung ausgelöst, wenn die Anwendung bereits aktiv ist. 
    ' NetworkAvailabilityChanged: Wird beim Herstellen oder Trennen der Netzwerkverbindung ausgelöst.
    Partial Friend Class MyApplication
        Private Logger As Logger

        Private ReadOnly CommonAppDataPath As String = Windows.Forms.Application.CommonAppDataPath
        Private ReadOnly StartupPath As String = Windows.Forms.Application.StartupPath

        Private ReadOnly Property Prefix
            Get
                Return My.Settings.UserConfig_Prefix
            End Get
        End Property

        Private ReadOnly Property HasPrefix
            Get
                Return TypeOf Prefix Is String AndAlso Prefix.Length > 0
            End Get
        End Property

        Public ReadOnly Property UserAppDataPath As String
            Get
                If HasPrefix Then
                    Return Combine(Windows.Forms.Application.UserAppDataPath, Prefix)
                Else
                    Return Windows.Forms.Application.UserAppDataPath
                End If
            End Get
        End Property

        Public ReadOnly Property LocalUserConfigPath As String
            Get
                If HasPrefix Then
                    Return Combine(Windows.Forms.Application.LocalUserAppDataPath, Prefix)
                Else
                    Return Windows.Forms.Application.LocalUserAppDataPath
                End If
            End Get
        End Property

        Public Sub App_Startup() Handles Me.Startup
            Dim oLogConfig As New LogConfig(LogPath:=PathType.CustomPath,
                                            CustomLogPath:=Combine(LocalUserConfigPath, "Log"),
                                            CompanyName:="Digital Data",
                                            ProductName:="ZooFlow",
                                            FileKeepRangeInDays:=30) With {.Debug = True}

            ' System Config files like Service Url will be saved in %LocalAppdata% so they will remain on the machine
            Dim oConfigManager As New ConfigManager(Of SystemConfig)(oLogConfig, UserAppDataPath, CommonAppDataPath, StartupPath)

            ' Layout files will be saved in %Appdata% (Roaming) so they will be syncronized with the user profile
            Dim oUIConfigPath = IO.Path.Combine(UserAppDataPath, ClassConstants.FOLDER_NAME_LAYOUT)
            Dim oUIConfigAlternatePath = IO.Path.Combine(UserAppDataPath, ClassConstants.FOLDER_NAME_LAYOUT)
            Dim oUIConfigManager As New ConfigManager(Of UIConfig)(oLogConfig, oUIConfigPath, oUIConfigPath, oUIConfigAlternatePath)

            LogConfig = oLogConfig
            LogConfig.Debug = True

            SystemConfigManager = oConfigManager
            UIConfigManager = oUIConfigManager

            Logger = LogConfig.GetLogger()
            Logger.Debug("Starting ZooFlow...")

            ProfileOptimization.SetProfileRoot("E:\Zooflow")
            ProfileOptimization.StartProfile("Startup.Profile")

            If oConfigManager.Config.AppServerConfig <> String.Empty Then
                Try
                    Dim oSplit() As String = oConfigManager.Config.AppServerConfig.ToString.Split(":"c)
                    Dim oAppServerAddress As String = oSplit(0)
                    Dim oAppServerPort As Integer = 9000
                    If oSplit.Length = 2 Then
                        oAppServerPort = oSplit(1)
                    End If

                    My.Application.Service.Client = New Client(LogConfig, oAppServerAddress, oAppServerPort)
                    If Not IsNothing(My.Application.Service.Client) Then
                        My.Application.Service.Client.Connect()
                    End If
                Catch ex As Exception
                    Logger.Warn($"Could not initialize the AppServer: {ex.Message}")
                End Try
            End If

            Dim oCommandLineArgs As New ClassCommandlineArgs(LogConfig)
            Dim oArgs = Environment.GetCommandLineArgs().Skip(1).ToList()
            oCommandLineArgs.Parse(oArgs)

            CommandLineFunction = oCommandLineArgs.FunctionName
            CommandLineArguments = oCommandLineArgs.FunctionArgs
        End Sub

        Public Sub App_Shutdown(sender As Object, e As EventArgs) Handles Me.Shutdown
            Logger.Debug("Shutting down Zooflow..")
        End Sub

        Private Sub MyApplication_UnhandledException(sender As Object, e As UnhandledExceptionEventArgs) Handles Me.UnhandledException
            Logger.Warn("Unhandled exception occurred: [{0}]", e.Exception.Message)
            Logger.Error(e.Exception)
        End Sub

    End Class
End Namespace