Imports System.Windows.Forms.VisualStyles.VisualStyleElement
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.EDMI.API
Imports DigitalData.Modules.EDMI.API.Constants
Imports DigitalData.Modules.EDMI.API.DatabaseWithFallback
Imports DigitalData.Modules.Logging
Imports DLLLicenseManager
Imports DocumentFormat.OpenXml.Spreadsheet

Public Class ClassInit
    Public _lizenzManager As ClassLicenseManager
    'Private DataASorDB As ClassDataASorDB

    <STAThread()>
    Public Sub InitLogger()
        Dim oLocalUserAppDataPath As String = Application.LocalUserAppDataPath
        LOGCONFIG = New LogConfig(LogConfig.PathType.CustomPath,
                                       oLocalUserAppDataPath & "\Log",
                                       My.Settings.UserConfig_Prefix,
                                        My.Application.Info.CompanyName,
                                        My.Application.Info.ProductName)

        LOGGER = LOGCONFIG.GetLogger("taskFLOW")
        LOGGER.Info("## taskFLOW started - {0}", Now)
        Try
            Dim directory As New IO.DirectoryInfo(Application.LocalUserAppDataPath & "\Log")
            For Each file As IO.FileInfo In directory.GetFiles
                If (Now - file.CreationTime).Days > 29 Then
                    file.Delete()
                Else
                    Exit For
                End If
            Next
        Catch ex As Exception

        End Try
    End Sub

    <STAThread()>
    Public Sub InitUserConfig()
        Try
            Dim oUserAppDataPath As String = Application.UserAppDataPath
            If My.Settings.UserConfig_Prefix <> String.Empty Then
                oUserAppDataPath += "\" + My.Settings.UserConfig_Prefix
            End If
            Dim oCommonAppDataPath = Application.CommonAppDataPath
            Dim oStartupPath = Application.StartupPath

            ' If AppConfig from Startup Path should be forced, rewrite the common app data path
            If My.Settings.UseAppConfigConString = True Then
                ' UserAppDataPath = StartupPath
                oCommonAppDataPath = oStartupPath
            End If

            CONFIG = New ConfigManager(Of ClassConfig)(LOGCONFIG, oUserAppDataPath, oCommonAppDataPath, oStartupPath)
            LOGGER.Info("ConfigManager loaded")
            LOGGER.Info($"oUserAppDataPath will be: {oUserAppDataPath}")

            If oStartupPath <> oCommonAppDataPath Then
                LOGGER.Info($"oCommonAppDataPath will be: {oCommonAppDataPath}")
                LOGGER.Info($"oStartupPath will be: {oStartupPath}")
            Else
                LOGGER.Info($"oStartupPath is the same as oCommonAppDataPath: {oCommonAppDataPath}")
            End If

            Try
                If CONFIG.Config.ConnectionStringTest <> String.Empty And CONFIG.Config.TestMode = True Then
                    LOGGER.Debug("Test Connection String loaded")
                    CONNECTION_STRING_ECM = DecryptConnectionString(CONFIG.Config.ConnectionStringTest)
                Else
                    LOGGER.Debug("Connection String loaded")
                    CONNECTION_STRING_ECM = DecryptConnectionString(CONFIG.Config.ConnectionString)
                End If
            Catch ex As Exception
                LOGGER.Error(ex, "Unexpected Error Getting CONFIG.TestMode or CONFIG.ConnectionStringTest")
            End Try

            Try
                If CONFIG.Config.EDMIAppServer <> String.Empty Then
                    Try
                        LOGGER.Info($"Configuration EDMIAppServer  [{CONFIG.Config.EDMIAppServer}] will be used...")

                        _Client = New Client(LOGCONFIG, CONFIG.Config.EDMIAppServer)
                        If Not IsNothing(_Client) Then
                            If _Client.Connect() Then
                                EDMIAppServerActive = True
                                EDMIService.Client = _Client
                                EDMIService.Address = CONFIG.Config.EDMIAppServer

                                LOGGER.Info($"EDMIAppServer [{CONFIG.Config.EDMIAppServer}] is active!")
                            Else
                                LOGGER.Warn($"#### ⚠️ !!! Could not Connect to APPServer [{CONFIG.Config.EDMIAppServer}]!!! ###")
                            End If
                        End If
                    Catch ex As Exception
                        LOGGER.Warn($"⚠️ Could not initialize the AppServer: {ex.Message}")
                    End Try

                Else
                    LOGGER.Debug("No EDMI Server Address. (String.empty).")
                End If
            Catch ex As Exception
                LOGGER.Error(ex, "Unexpected Error Getting CONFIG.EDMIAppServer")
            End Try



            INDEX_DMS_ERSTELLT = CONFIG.Config.IndexDmsErstellt
            INDEX_DMS_ERSTELLT_ZEIT = CONFIG.Config.IndexDmsErstelltZeit

            USER_CONFIG_DEBUG = CONFIG.Config.DEBUG
            If USER_CONFIG_DEBUG = True Then
                DEBUG = True
                LOGCONFIG.Debug = True
            End If

            USER_CONFIG_DIRECTORY = CONFIG.UserConfigPath.Replace("UserConfig.xml", "")
            If USER_LANGUAGE <> String.Empty Then
                USER_CONFIG_DIRECTORY = System.IO.Path.Combine(USER_CONFIG_DIRECTORY, USER_LANGUAGE)
            End If
            Try
                If Not System.IO.Directory.Exists(USER_CONFIG_DIRECTORY) Then
                    System.IO.Directory.CreateDirectory(USER_CONFIG_DIRECTORY)
                End If
            Catch ex As Exception
                LOGGER.Error(ex)
            End Try

        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub

    Private Function DecryptConnectionString(EncryptedConnectionString As String) As String
        Dim oBuilder As New SqlClient.SqlConnectionStringBuilder With {
            .ConnectionString = EncryptedConnectionString
        }

        If oBuilder.ConnectionString.Contains("Password=") Then
            Dim oPlaintextPassword As String
            Dim oDecryptor As New ClassEncryption("!35452didalog=")

            Try
                oPlaintextPassword = oDecryptor.DecryptData(oBuilder.Password)
            Catch ex As Exception
                LOGGER.Error(ex)
                LOGGER.Debug("Password {0} could not be decrypted. Assuming plaintext password.")
                oPlaintextPassword = oBuilder.Password
            End Try
            Return EncryptedConnectionString.Replace(oBuilder.Password, oPlaintextPassword)
        Else
            Return EncryptedConnectionString
        End If
    End Function

    <STAThread()>
    Public Function InitDatabase(GetCSFromAppServ As Boolean)
        If GetCSFromAppServ = True Then
            LOGGER.Info("Getting DatabaseInfo from ApplicationServer...")
        End If
        Dim Database_ECM As MSSQLServer = Nothing
        Dim Database_IDB As MSSQLServer = Nothing
        If GetCSFromAppServ = False Then
            If CONNECTION_STRING_ECM = String.Empty Then
                MsgBox("No Databaseconnection configured. (First Start or Appdata not accessible)" & vbNewLine & "Basic-Config will be loaded.", MsgBoxStyle.Information)
                ERROR_STATE = "NO DB-CONNECTION"
                frmKonfig.ShowDialog()
            End If
        End If

        Dim oCSECM As String
        If GetCSFromAppServ = False Then
            oCSECM = CONNECTION_STRING_ECM
        Else
            oCSECM = EDMIService.Client.ClientConfig.ConnectionStringECM
            CONNECTION_STRING_ECM = oCSECM
        End If

        Database_ECM = New MSSQLServer(LOGCONFIG, oCSECM)
        If Database_ECM.DBInitialized = True Then
            dbECMInitialized = True
            DatabaseECM = Database_ECM
        Else
            dbECMInitialized = False
        End If
        If dbECMInitialized = False Then
            ERROR_STATE = "FAILED DBCONNECTION"
            MsgBox("Error in InitDatabase. (Connection DD_ECM failed) More information in the logfile.", MsgBoxStyle.Critical)
            Return False
        End If
        If GetCSFromAppServ = True Or (GetCSFromAppServ = False And CONNECTION_STRING_IDB <> String.Empty) Then
            Dim oCSIDB As String
            If GetCSFromAppServ = False Then
                oCSIDB = CONNECTION_STRING_IDB
            Else
                oCSIDB = EDMIService.Client.ClientConfig.ConnectionStringIDB
            End If
            Database_IDB = New MSSQLServer(LOGCONFIG, oCSIDB)
            If Database_IDB.DBInitialized = True Then
                CONNECTION_STRING_IDB = oCSIDB
                DatabaseIDB = Database_IDB
                dbIDBInitialized = True
                IDB_ACTIVE = True
                LOGGER.Info("IDB is active via Config")

            End If
        End If




        ' We initialize the Class in anycase.
        ' If there is no client, it will fall back to the db by itself
        DatabaseFallback = New DatabaseWithFallback(LOGCONFIG, _Client, Database_ECM, Database_IDB)

        If dbECMInitialized = True And CONNECTION_STRING_IDB = String.Empty Then
            Return True
        ElseIf dbECMInitialized = True And CONNECTION_STRING_IDB <> String.Empty Then
            If dbIDBInitialized = True Then
                Return True
            Else
                MsgBox("Error in InitDatabase. (Connection IDB failed) More information in the logfile.", MsgBoxStyle.Critical)
                Return False
            End If

        End If

    End Function

    <STAThread()>
    Sub Refresh_Licence()
        Dim oStopWatch As New RefreshHelper.SW("Refresh_Licence")
        Try
            Me._lizenzManager = New ClassLicenseManager("#DigitalData35452!#", "")
            Dim lic As String = BASEDATA_DT_CONFIG.Rows(0).Item("LIZENZEN")
            Dim licString = Me._lizenzManager.DecodeLicenseKey(lic)
            Dim split() = licString.ToString.Split("#")

            If lic <> "" Then
                LICENSE_COUNT = split(0)
            Else
                LICENSE_COUNT = 0
            End If
            If split.Length >= 2 Then
                LICENSE_VALID = True
            End If
            Dim oLICDATE As Date
            Try
                oLICDATE = CDate(split(1))
            Catch ex As Exception
                LOGGER.Warn($"⚠️ Error Converting Value {split(1)} to DATE")
                Try
                    Dim expenddt As Date = Date.ParseExact(split(1), "dd.MM.yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo)
                    oLICDATE = expenddt
                Catch ex1 As Exception
                    LOGGER.Warn($"⚠️Second Error Converting DATE with ParseExact - Setting Date = Today")
                    oLICDATE = Now.Date
                End Try

            End Try

            If oLICDATE < CDate(Now) Then
                MsgBox("Your license has expired!" & vbNewLine & "Last valid date: " & split(1) & vbNewLine & "Please contact Your sysadmin", MsgBoxStyle.Exclamation)
                LICENSE_EXPIRED = True
                LICENSE_COUNT = 0
            ElseIf LICENSE_VALID = False Then
                MsgBox("Your license is invalid!" & vbNewLine & "Please contact Your sysadmin", MsgBoxStyle.Exclamation)
                LICENSE_EXPIRED = True
                LICENSE_COUNT = 0
            End If

            LOGGER.Debug("license initialized....")

            LICENSE_PROFILES = split(2)

            Try
                Dim oMod = split(3)
                If Not IsNothing(split(3)) Then
                    LIC_MODULES = split(3)
                End If
            Catch ex As Exception

            End Try
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Unexpected error in Refresh license: " & ex.Message, True)
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Fehler bei Licensemanager:")
        End Try
        oStopWatch.Done()
    End Sub
    <STAThread()>
    Public Sub InitUserLogin()
        Dim oStopWatch As New RefreshHelper.SW("InitUserLogin")
        Dim oSQL As String
        Try
            If USER_GHOST_MODE_USRNAME <> String.Empty Then
                LOGGER.Info($"InitUserLogin with GhostUser [{USER_GHOST_MODE_USRNAME}]")
                USER_USERNAME = USER_GHOST_MODE_USRNAME
            Else
                USER_USERNAME = Environment.UserName
            End If

            Try
                oSQLLoginAttempt = String.Format($"INSERT INTO TBDD_USER_LOG_IN_ATTEMPT (USERNAME,MODULE,VERSION_CLIENT,MACHINE_NAME,OVERRIDE_LANGUAGE, APP_STARTUP_PATH) VALUES 
                    ('{USER_USERNAME}','{MODULE_PM}','{My.Application.Info.Version.ToString}','{Environment.MachineName}','','{Application.StartupPath}')")

                Dim oSQLSW As New RefreshHelper.SW("VWDD_USER_CLIENT")
                oSQL = $"SELECT * FROM VWDD_USER_CLIENT WHERE USERNAME = '{USER_USERNAME}'"

                DT_CLIENT_USER = DatabaseFallback.GetDatatable("VWDD_USER_CLIENT", New GetDatatableOptions(oSQL, DatabaseType.ECM) With {
                    .FilterExpression = $"USERNAME = '{USER_USERNAME}'"
                })
                'DT_CLIENT_USER = DataASorDB.GetDatatable("DD_ECM", oSQL, "VWDD_USER_CLIENT", $"USERNAME like '{USER_USERNAME}'")
                oSQLSW.Done()

                If DT_CLIENT_USER.Rows.Count > 1 Then
                    frmClientLogin.ShowDialog()
                ElseIf DT_CLIENT_USER.Rows.Count = 1 Then
                    CLIENT_SELECTED = DT_CLIENT_USER.Rows(0).Item("CLIENT_ID")
                Else
                    DatabaseECM.ExecuteNonQuery(oSQLLoginAttempt)
                    ERROR_STATE = "NO CLIENT"
                    Dim oDT As DataTable = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("No Client relation")
                    MsgBox(oDT.Rows(0).Item("STRING1") & vbNewLine & oDT.Rows(0).Item("STRING2") & vbNewLine & vbNewLine & oSQL, MsgBoxStyle.Exclamation)
                    Exit Sub
                End If
            Catch ex As Exception
                LOGGER.Error(ex)
                LOGGER.Info("Unexpected error in checking CLIENT: " & ex.Message)
                CLIENT_SELECTED = 1
            End Try

            LOGGER.Debug("Username: " & USER_USERNAME)
            Dim oFnct As New RefreshHelper.SW("FNDD_LOGIN_USER_MODULE")
            oSQL = String.Format("SELECT * FROM [dbo].[FNDD_LOGIN_USER_MODULE] ('{0}','PM',{1})", USER_USERNAME, CLIENT_SELECTED)

            Dim DT_CHECKUSER_MODULE As DataTable
            DT_CHECKUSER_MODULE = DatabaseFallback.GetDatatable("TBDD_USER_MODULE", New GetDatatableOptions(oSQL, DatabaseType.ECM) With {
                               .FilterExpression = $"USERNAME = '{USER_USERNAME.ToLower}' AND MODULE_SHORT = 'PM'"
                           })

            oFnct.Done()
            If DT_CHECKUSER_MODULE.Rows.Count = 0 Then
                DatabaseECM.ExecuteNonQuery(oSQLLoginAttempt)
                LOGGER.Info("DT_CHECKUSER_MODULE.Rows.Count = 0", True)
                ERROR_STATE = "NO USER"
                MsgBox("Sorry - Something went wrong in getting Your rights." & vbNewLine & "Please contact the system administrator!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If


            If DT_CHECKUSER_MODULE.Rows.Count = 1 Then
                LOGGER.Info($"Got a CheckUserDefintion for User [{USER_USERNAME}]")


                USER_ID = DT_CHECKUSER_MODULE.Rows(0).Item("USER_ID")
                USER_SURNAME = IIf(IsDBNull(DT_CHECKUSER_MODULE.Rows(0).Item("USER_SURNAME")), "", DT_CHECKUSER_MODULE.Rows(0).Item("USER_SURNAME"))
                USER_PRENAME = IIf(IsDBNull(DT_CHECKUSER_MODULE.Rows(0).Item("USER_PRENAME")), "", DT_CHECKUSER_MODULE.Rows(0).Item("USER_PRENAME"))
                USER_SHORTNAME = IIf(IsDBNull(DT_CHECKUSER_MODULE.Rows(0).Item("USER_SHORTNAME")), "", DT_CHECKUSER_MODULE.Rows(0).Item("USER_SHORTNAME"))
                USER_EMAIL = IIf(IsDBNull(DT_CHECKUSER_MODULE.Rows(0).Item("USER_EMAIL")), "", DT_CHECKUSER_MODULE.Rows(0).Item("USER_EMAIL"))
                USER_LANGUAGE = DT_CHECKUSER_MODULE.Rows(0).Item("USER_LANGUAGE")

                USER_MODULE_ID = DT_CHECKUSER_MODULE.Rows(0).Item("MODULE_ID")


                USER_IN_MODULE = DT_CHECKUSER_MODULE.Rows(0).Item("MODULE_ACCESS")
                If USER_IN_MODULE = True Then
                    USER_EXISTS = True
                Else
                    USER_EXISTS = False
                End If


                USER_IS_ADMIN = DT_CHECKUSER_MODULE.Rows(0).Item("IS_ADMIN")

                User.IsAdmin = USER_IS_ADMIN
                User.Surname = USER_SURNAME
                User.GivenName = USER_PRENAME
                User.Email = USER_EMAIL
                User.UserName = USER_USERNAME
                User.UserId = USER_ID
                User.Language = USER_LANGUAGE

                LOGGER.Debug("User Info:")
                LOGGER.Debug("Language: [{0}]", USER_LANGUAGE)
                LOGGER.Debug("Username: [{0}]", USER_USERNAME)
                LOGGER.Debug("Environment.MachineName: [{0}]", Environment.MachineName)

                Try
                    USER_RIGHT_FILE_DELETE = IIf(IsDBNull(DT_CHECKUSER_MODULE.Rows(0).Item("USER_RIGHT_FILE_DEL")), False, DT_CHECKUSER_MODULE.Rows(0).Item("USER_RIGHT_FILE_DEL"))

                Catch ex As Exception
                    LOGGER.Warn("⚠️ Error in USER_RIGHT_FILE_DELETE: " & ex.Message)
                    USER_RIGHT_FILE_DELETE = False
                End Try
                USER_DATE_FORMAT = DT_CHECKUSER_MODULE.Rows(0).Item("USER_DATE_FORMAT")


                ClassParamRefresh.Refresh_Params(DT_CHECKUSER_MODULE, "Load")


                FINALINDICES = New ClassFinalIndex()
                FINALINDICES.init()


                Try
                    USER_RIGHT_VIEW_ONLY = DT_CHECKUSER_MODULE.Rows(0).Item("USER_RIGHT2")
                    LOGGER.Debug("USER_RIGHT_VIEW_ONLY: " & USER_RIGHT_VIEW_ONLY.ToString)
                Catch ex As Exception
                    USER_RIGHT_VIEW_ONLY = False
                    LOGGER.Info("⚠️ Error in USER_RIGHT_VIEW_ONLY: " & ex.Message)
                End Try
                Try
                    USER_RIGHT3 = DT_CHECKUSER_MODULE.Rows(0).Item("USER_RIGHT3")
                Catch ex As Exception
                    USER_RIGHT3 = False
                    LOGGER.Info("⚠️ Error in USER_RIGHT3: " & ex.Message)
                End Try
                Try
                    USER_RIGHT4 = DT_CHECKUSER_MODULE.Rows(0).Item("USER_RIGHT4")
                Catch ex As Exception
                    USER_RIGHT4 = False
                    LOGGER.Info("⚠️ Error in USER_RIGHT4: " & ex.Message)
                End Try
                LOGGER.Debug("User exists....")

                'Am System anmelden
                Refresh_Licence()
                'Check_User_Exists_in_PMGroups()
                'Dim Culture = CultureInfo.CreateSpecificCulture("en-US")
                '' The following line provides localization for the application's user interface. 
                'Thread.CurrentThread.CurrentUICulture = Culture
                '' The following line provides localization for data formats. 
                'Thread.CurrentThread.CurrentCulture = Culture
                '' Set this culture as the default culture for all threads in this application.  
                '' Note: The following properties are supported in the .NET Framework 4.5+ 
                'CultureInfo.DefaultThreadCurrentCulture = Culture
                'CultureInfo.DefaultThreadCurrentUICulture = Culture


                If ClassAllgemeineFunktionen.LoginOut("LOGIN") = True Then
                    USERCOUNT_LOGGED_IN += 1
                End If
                LOGGER.Debug("Count Users logged in: " & USERCOUNT_LOGGED_IN.ToString)
                If LICENSE_COUNT < USERCOUNT_LOGGED_IN And LICENSE_EXPIRED = False Then
                    MsgBox("Die Anzahl der aktuell angemeldeten User (" & USERCOUNT_LOGGED_IN.ToString & ") überschreitet die Anzahl der aktuellen Lizenzen!" & vbNewLine & "Anzahl der Lizenzen: " & LICENSE_COUNT.ToString & vbNewLine & "Bitte setzen Sie sich mit dem Systembetreuer in Verbindung!", MsgBoxStyle.Critical, "Achtung:")
                    LOGGER.Info("Die Anzahl der aktuell angemeldeten User (" & USERCOUNT_LOGGED_IN.ToString & ") überschreitet die Anzahl der Lizenzen (" & LICENSE_COUNT & ") für Flow Task!")
                    If USER_IS_ADMIN = False Then
                        ClassAllgemeineFunktionen.LoginOut("LOGOUT")
                        DatabaseECM.ExecuteNonQuery(oSQLLoginAttempt)
                        ERROR_STATE = "START INCOMPLETE"
                    End If
                End If

                'Alles OK bis hierhin...nun die FolderwatchKonfig laden
                LOGGER.Debug("Init Userlogin successfull completed....")
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Unexpected Error in InitUserLogin: " & ex.Message, True)
            DatabaseECM.ExecuteNonQuery(oSQLLoginAttempt)
            ERROR_STATE = "START INCOMPLETE"
        End Try
        oStopWatch.Done()
    End Sub
    <STAThread()>
    Public Sub InitBasics()
        Dim oStep As String
        Try
            'If IsNothing(DataASorDB) Then
            '    DataASorDB = New ClassDataASorDB
            'End If
            Dim oStopWatch As New RefreshHelper.SW("InitBasics")
            Dim oSql = String.Format("select * from TBPM_KONFIGURATION WITH (NOLOCK) WHERE GUID = 1")
            oStep = "TBPM_KONFIGURATION"

            BASEDATA_DT_CONFIG = DatabaseFallback.GetDatatable("TBPM_KONFIGURATION", New GetDatatableOptions(oSql, DatabaseType.ECM) With {
                .FilterExpression = $"GUID = 1"
            })
            WMSUFFIX = BASEDATA_DT_CONFIG.Rows.Item(0).Item("WM_REL_PATH")
            WMDRIVE_LETTER = BASEDATA_DT_CONFIG.Rows.Item(0).Item("WM_DRIVE_LETTER")
            Settings_LoadBasicConfig()

            oStep = "TBDD_CONNECTION"
            oSql = "select * from TBDD_CONNECTION WHERE AKTIV = 1"
            'BASEDATA_DT_TBDD_CONNECTION = DataASorDB.GetDatatable("DD_ECM", oSql, "TBDD_CONNECTION", "")
            BASEDATA_DT_TBDD_CONNECTION = DatabaseFallback.GetDatatable("TBDD_CONNECTION", New GetDatatableOptions(oSql, DatabaseType.ECM))

            oStep = "TBDD_CATALOG"
            oSql = "select CAT_TITLE,CAT_STRING from TBDD_CATALOG"
            BASEDATA_DT_TBDD_CATALOG = DatabaseFallback.GetDatatable("TBDD_CATALOG", New GetDatatableOptions(oSql, DatabaseType.ECM))

            For Each oROW As DataRow In BASEDATA_DT_TBDD_CATALOG.Rows

            Next

            oStep = "TBDD_3RD_PARTY_MODULES"
            oSql = "Select * FROM TBDD_3RD_PARTY_MODULES WHERE ACTIVE = 1"
            Dim oTBDD_3RD_PARTY_MODULES As DataTable
            'oTBDD_3RD_PARTY_MODULES = DataASorDB.GetDatatable("DD_ECM", oSql, "TBDD_3RD_PARTY_MODULES", "")
            oTBDD_3RD_PARTY_MODULES = DatabaseFallback.GetDatatable("TBDD_3RD_PARTY_MODULES", New GetDatatableOptions(oSql, DatabaseType.ECM))

            For Each oROW As DataRow In oTBDD_3RD_PARTY_MODULES.Rows
                If oROW.Item("NAME") = "GDPICTURE" And oROW.Item("VERSION") = My.Settings.GDPICTURE_VERSION Then
                    GDPICTURE_LICENSE = oROW.Item("LICENSE")
                End If
            Next
            If GDPICTURE_LICENSE = String.Empty Then
                LOGGER.Warn($"Keine GDPICTURE-Lizenz gefunden. Version Konfiguration: {My.Settings.GDPICTURE_VERSION} - Prüfe TBDD_3RD_PARTY_MODULES")
            End If
            oStep = "TBDD_SQL_COMMANDS"
            oSql = "Select * FROM TBDD_SQL_COMMANDS WITH (NOLOCK)"

            BASEDATA_DT_TBDD_SQL_COMMANDS = DatabaseFallback.GetDatatable("TBDD_SQL_COMMANDS", New GetDatatableOptions(oSql, DatabaseType.ECM))

            oStep = "TBDD_GUI_LANGUAGE_PHRASE"
            oSql = $"SELECT * FROM TBDD_GUI_LANGUAGE_PHRASE WITH (NOLOCK) WHERE MODULE IN ('PM','All Modules')"
            'BASEDATA_DT_GUI_LANGUAGE_PHRASES = DataASorDB.GetDatatable("DD_ECM", oSql, "TBDD_GUI_LANGUAGE_PHRASE", "")
            BASEDATA_DT_GUI_LANGUAGE_PHRASES = DatabaseFallback.GetDatatable("TBDD_GUI_LANGUAGE_PHRASE", New GetDatatableOptions(oSql, DatabaseType.ECM))
            oStep = "TBPM_PROFILE_SEARCH"
            oSql = "select * from TBPM_PROFILE_SEARCH WITH (NOLOCK) where TYPE = 'DOC' AND ACTIVE = 1 ORDER BY PROFILE_ID,TAB_INDEX"
            BASEDATA_DT_PROFILES_SEARCHES_DOC = DatabaseFallback.GetDatatable("TBPM_PROFILE_SEARCH", New GetDatatableOptions(oSql, DatabaseType.ECM) With {
                .SortByColumn = "PROFILE_ID,TAB_INDEX"
            })
            DT_FILTERED_PROFILE_SEARCHES_DOC = BASEDATA_DT_PROFILES_SEARCHES_DOC.Clone()

            oStep = "TBPM_MAIN_VIEW_GROUPS"
            oSql = "SELECT * FROM TBPM_MAIN_VIEW_GROUPS WITH (NOLOCK) WHERE ACTIVE = 1"

            BASEDATA_DTGRID_GROUPS = DatabaseFallback.GetDatatable("TBPM_MAIN_VIEW_GROUPS", New GetDatatableOptions(oSql, DatabaseType.ECM))


            oStep = "TBPM_CHART"
            oSql = "SELECT * FROM TBPM_CHART WITH (NOLOCK)"

            BASEDATA_DT_CHARTS = DatabaseFallback.GetDatatable("TBPM_CHART", New GetDatatableOptions(oSql, DatabaseType.ECM))
            oStep = "TBDD_GUI_LANGUAGE"
            oSql = "SELECT LANG_CODE FROM TBDD_GUI_LANGUAGE WITH (NOLOCK) WHERE ACTIVE = 1 ORDER BY LANG_CODE"

            BASEDATA_DT_LANGUAGE = DatabaseFallback.GetDatatable("TBDD_GUI_LANGUAGE", New GetDatatableOptions(oSql, DatabaseType.ECM))

            oSql = "SELECT * FROM TBDD_COLUMNS_FORMAT WITH (NOLOCK) WHERE MODULE = 'taskFLOW' AND GRIDVIEW = 'GridViewWorkflows'"
            BASEDATA_TBDD_COLUMNS_FORMAT = DatabaseFallback.GetDatatable("TBDD_COLUMNS_FORMAT", New GetDatatableOptions(oSql, DatabaseType.ECM))



            oStopWatch.Done()

        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info($"Unexpected Error in InitBasics - last Step [{oStep}]: {ex.Message}", True)
            DatabaseECM.ExecuteNonQuery(oSQLLoginAttempt)
            ERROR_STATE = "Basics not initialized"
        End Try
    End Sub
    <STAThread()>
    Public Sub InitBasics2()
        Try
            Dim oStopWatch As New RefreshHelper.SW("InitBasics2")
            Dim oSql = String.Format("SELECT * FROM VWPM_PROFILE_USER WHERE USER_ID = {0}", USER_ID)
            BASEDATA_DT_VW_PROFILE_USER = DatabaseFallback.GetDatatable("VWPM_PROFILE_USER", New GetDatatableOptions(oSql, DatabaseType.ECM) With {
                .FilterExpression = $"USER_ID = {USER_ID}"
            })

            If BASEDATA_DT_VW_PROFILE_USER.Rows.Count = 0 Then
                LOGGER.Warn($"no profiles for user: '{USER_USERNAME}' configured - Check SQL [{oSql}]!", False)
            End If

            oSql = "SELECT KEY_NAME, VALUE_TEXT1 
                             FROM TBDD_USER_KEY_VALUE_PAIR WITH (NOLOCK)
                             WHERE FK_USER_ID = " & USER_ID & " And [FK_MODULE_ID] = '" & USER_MODULE_ID & "'"

            Dim oDT_USER_KEY_VALUE_PAIR As DataTable = DatabaseFallback.GetDatatable(New GetDatatableOptions(oSql, DatabaseType.ECM))
            If UserInheritance_ConfirmationByColumn Is Nothing Then
                UserInheritance_ConfirmationByColumn = New List(Of UserInheritanceConfirmation)()
            End If
            If Not IsNothing(oDT_USER_KEY_VALUE_PAIR) Then
                For Each row As DataRow In oDT_USER_KEY_VALUE_PAIR.Rows
                    Dim keyName As String = row("KEY_NAME").ToString()

                    ' Prüfe ob es sich um einen Inheritance-Key handelt
                    If keyName.StartsWith("INHERITANCE_CONFIRM_") Then
                        Dim columnName As String = keyName.Replace("INHERITANCE_CONFIRM_", "")
                        Dim countValue As Integer = Integer.Parse(row("VALUE_TEXT1").ToString())

                        Dim existingEntry = UserInheritance_ConfirmationByColumn.FirstOrDefault(
                    Function(e) String.Equals(e.ColumnName, columnName, StringComparison.OrdinalIgnoreCase))

                        If existingEntry IsNot Nothing Then
                            existingEntry.Count = countValue
                        Else
                            UserInheritance_ConfirmationByColumn.Add(
                        New UserInheritanceConfirmation With {
                            .ColumnName = columnName,
                            .Count = countValue
                        })
                        End If

                        LOGGER.Debug("Loaded inheritance confirmation for column [{0}] with count [{1}]", columnName, countValue)
                    End If
                Next
            Else
                LOGGER.Warn("⚠️ oDT_USER_KEY_VALUE_PAIR is nothing")
            End If






            oStopWatch.Done()
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Unexpected Error in InitBasics2: " & ex.Message, True)
            DatabaseECM.ExecuteNonQuery(oSQLLoginAttempt)
            ERROR_STATE = "Basics2 not initialized"
        End Try
    End Sub
    <STAThread()>
    Private Function Settings_LoadBasicConfig()
        Try
            Dim oSql As String = "select * from tbdd_Modules WITH (NOLOCK) where SHORT_NAME = 'PM'"
            Dim oDTtbdd_Modules As DataTable
            'oDTtbdd_Modules = DataASorDB.GetDatatable("DD_ECM", oSql, "tbdd_Modules", $" SHORT_NAME = 'PM'")
            oDTtbdd_Modules = DatabaseFallback.GetDatatable("TBDD_MODULES", New GetDatatableOptions(oSql, DatabaseType.ECM) With {
                .FilterExpression = $" SHORT_NAME = 'PM'"
            })

            If oDTtbdd_Modules.Rows.Count = 1 Then
                Try
                    VERSION_DELIMITER = oDTtbdd_Modules.Rows(0).Item("VERSION_DELIMITER")
                    FILE_DELIMITER = oDTtbdd_Modules.Rows(0).Item("FILE_DELIMITER")
                    LICENSE_VALID = oDTtbdd_Modules.Rows(0).Item("LICENSE_VALID")
                    WMSESSION_STARTSTOP_STARTUP = oDTtbdd_Modules.Rows(0).Item("WMSESSION_STARTSTOP_STARTUP")
                Catch ex As Exception
                    LOGGER.Error(ex)
                    LOGGER.Info("Unexpected Error in Settings_LoadBasicConfig: " & ex.Message, True)
                End Try
            Else
                Return False
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Error in Settings_LoadBasicConfig" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
        Return True
    End Function

End Class
