Imports System.IO
Imports DD_LIB_Standards
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging

Public Class ClassInit
    Public Sub New()
    End Sub

    Public Sub InitLoggerANDConfig()
        Try
            LOGCONFIG = New LogConfig(LogConfig.PathType.AppData, Nothing, Nothing,
                                        My.Application.Info.CompanyName,
                                        "OrgFlow")
            LOGGER = LOGCONFIG.GetLogger()
            LOGGER.Info("OrgFlow started")

            Dim oUserAppDataPath As String = Application.UserAppDataPath
            Dim oLegacyAppDataPath As String = Application.UserAppDataPath
            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("Config loaded")

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

        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub
    Private Shared 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
    Public Shared Function InitDatabase()
        Try
            'Dim dbResult As Boolean

            MySettings_Load()

            If LoadFileExclusion() = False Then
                MsgBox("The Exclude File Structure for files in Folderwatch could not be initialized!", MsgBoxStyle.Information)
            End If
            clsDatabase.GUI = True
            If CONFIG.Config.ConnectionString <> String.Empty Then
                LOGGER.Debug("Connection String from CONFIG")
                MyConnectionString = DecryptConnectionString(CONFIG.Config.ConnectionString)
            End If
            If MyConnectionString <> String.Empty Then
                MYDB_ECM = New MSSQLServer(LOGCONFIG, MyConnectionString)
                If MYDB_ECM.DBInitialized = False Then
                    frmConfig_Basic.ShowDialog()
                End If
                ' dbResult = clsDatabase.Init(MyConnectionString)
            Else
                frmConfig_Basic.ShowDialog()
                ' dbResult = clsDatabase.Init(MyConnectionString)
            End If
            If ClassProxy.MyPROXYConnectionString <> String.Empty Then
                If clsDatabase.Init(ClassProxy.MyPROXYConnectionString, True) = False Then
                    ClassHelper.MSGBOX_Handler("ERROR", "", "Error while Initializing proxyserver - Check logfile")
                Else
                    Dim csb As New SqlClient.SqlConnectionStringBuilder
                    csb.ConnectionString = ClassProxy.MyPROXYConnectionString
                    ClassHelper.InsertEssential_Log(USER_GUID, "USER-ID", String.Format("Proxy-Server {0} - Database {1} is used", csb.DataSource, csb.InitialCatalog))
                End If
            End If
            If Not IsNothing(MYDB_ECM) Then
                If MYDB_ECM.DBInitialized = False Then
                    If clsLogger.LOGG_MSG <> String.Empty Then
                        Throw New Exception("Error while Initializing database:" & vbNewLine & clsLogger.LOGG_MSG)
                    Else
                        Throw New Exception("Find more information in the logfile.")
                    End If

                End If
            Else
                Return False
            End If

            Return True
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Unexpected Error in Init Database:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try

    End Function

    Public Sub InitAddons()
        Try
            Dim CurrentDir As String = My.Application.Info.DirectoryPath

            Dim AddonPath As String = MY_ADDON_PATH ' MYDB_ECM.GetScalarValue(SQL)
            Dim Dev_AddonPath As String = System.IO.Path.GetFullPath(System.IO.Path.Combine(CurrentDir, "..\..\..\..\app"))

            If AddonPath Is Nothing OrElse AddonPath = "" Then
                ' Addon Pfad in der Datenbank ist leer
                Dim path = System.IO.Path.Combine(CurrentDir, "Addons")
                Dim AddonDir As New DirectoryInfo(path)

                If AddonDir.Exists Then
                    AddonPath = path
                Else
                    AddonPath = Dev_AddonPath
                End If
            Else
                ' Addon Pfad steht in der Datenbank
                Dim path = AddonPath
                Dim AddonDir As New DirectoryInfo(path)

                If (AddonDir.Exists) Then
                    If AddonDir.Name = "Addons" Then
                        AddonPath = path
                    Else
                        AddonPath = Dev_AddonPath
                    End If
                Else
                    AddonPath = Dev_AddonPath
                End If
            End If

            MY_ADDON_PATH = AddonPath
            SaveMySettingsValue("PATH_ADDON", MY_ADDON_PATH, "ConfigMain")
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Unexpected Error in InitAddons:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Public Sub InitBasics2()
        Try
            Dim configResult As Boolean
            configResult = Settings_LoadBasicConfig()

            If configResult = False Then
                Throw New Exception("Find more information in the logfile.")
            End If

            Dim sql = String.Format("SELECT * FROM TBPMO_KONFIGURATION WHERE GUID = 1")
            Dim KONFIG_DT As DataTable = MYDB_ECM.GetDatatable(sql)
            If KONFIG_DT.Rows.Count = 1 Then
                Try
                    MY_WIKISTRING = KONFIG_DT.Rows(0).Item("WIKI_STRING")

                Catch ex As Exception
                    MY_WIKISTRING = ""
                End Try
                WD_UNICODE = KONFIG_DT.Rows(0).Item("WD_UNICODE")
                SQL_FULLTEXT = KONFIG_DT.Rows(0).Item("SQL_FULLTEXT")
                WMDriveLetter = KONFIG_DT.Rows(0).Item("WM_LAUFWERKBUCHSTABE")
                WMPATH_PREFIX = KONFIG_DT.Rows(0).Item("WMPATH_PREFIX")
                If Not WMPATH_PREFIX.ToUpper.StartsWith("\\WINDREAM\OBJECTS") Then
                    SHARE_DRIVE_ACTIVE = True
                    LOGGER.Info("WM SHARE_DRIVE via TBPMO_KONFIGURATION is active")
                End If
            End If

            sql = "SELECT * FROM TBDD_SQL_COMMANDS"
            Dim oDTSQL_COMMANDS As DataTable = MYDB_ECM.GetDatatable(sql)
            For Each oRow As DataRow In oDTSQL_COMMANDS.Rows
                If oRow.Item("TITLE") = "ADDI_DOC_SEARCH_RECORD" Then
                    SQL_DOC_RESULT_RECORD = oRow.Item("SQL_COMMAND")
                    LOGGER.Debug("SQL_DOC_RESULT_RECORD = " + SQL_DOC_RESULT_RECORD)
                End If
            Next
            sql = "SELECT * FROM TBPMO_CONTROL"
            CURRENT_TBPMO_CONTROL = MYDB_ECM.GetDatatable(sql)
            sql = String.Format("SELECT * FROM TBPMO_DOCSEARCH_RESULTLIST_CONFIG WHERE VISIBLE = 1")
            DT_DOCSEARCH_RESULTLIST_CONFIG = MYDB_ECM.GetDatatable(sql)
            sql = String.Format("SELECT * FROM TBPMO_DOCSEARCH_VARIABLE_CONTROLS")
            CURRENT_VARIABLE_CONTROLS = MYDB_ECM.GetDatatable(sql)
            sql = String.Format("SELECT * FROM TBPMO_FORM_VIEW")
            CURRENT_TBPMO_FORM_VIEW = MYDB_ECM.GetDatatable(sql)
            sql = String.Format("select T.*, T1.HEADER_CAPTION,T1.TYPE_ID ,T1.ENTITY_ID,T1.LANGUAGE from TBPMO_DOCRESULT_DROPDOWN_ITEMS T, TBPMO_DOCSEARCH_RESULTLIST_CONFIG T1 WHERE T.CONFIG_ID = T1.GUID")
            CURRENT_TBPMO_DOCRESULT_DROPDOWN_ITEMS = MYDB_ECM.GetDatatable(sql)
            clsCURRENT.LOG_ERRORS_ONLY = DEBUG

            sql = String.Format("select* from TBPMO_FILE_FORMATS_CHANGE")
            Dim oDTFF_CHANGE As DataTable = MYDB_ECM.GetDatatable(sql)
            For Each oRow As DataRow In oDTFF_CHANGE.Rows
                FILE_FORMATS_CHANGE_DURING_EDIT.Add(oRow.Item("FILE_EXT"))
            Next

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

    End Sub

    Public Shared Sub Init_CONN_SWITCH()
        Try
            Dim sql = String.Format("SELECT T1.GUID, T.DESCRIPTION, T.SQL_CONNECTION, T.SQL_CONNECTION_PROXY, T.WM_ALIAS,T1.ACTIVE FROM " &
                                    "TBPMO_CLIENT_CONNECTION_SWITCH T, TBPMO_CLIENT_CONN_SWITCH_USER T1 WHERE T.GUID = T1.CONN_SWITCH_ID " &
                                    "And T.ACTIVE = 1 And T1.USER_ID = {0}", USER_GUID)
            CURRENT_TBPMO_CONN_SWITCH = MYDB_ECM.GetDatatable(sql)
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Warn("Unexpected Error in Init_CONN_SWITCH: " & ex.Message)
        End Try
    End Sub

    Public Shared Function InitUserLogin(Optional _User As String = "")
        Try

            If _User = "" Then
                USER_USERNAME = Environment.UserName
            Else
                USER_USERNAME = _User
            End If

            Dim sql = String.Format("SELECT T.*, T1.IS_ADMIN FROM TBDD_USER T INNER JOIN TBDD_USER_MODULES T1 ON T.GUID = T1.USER_ID INNER JOIN TBDD_MODULES T2 ON T1.MODULE_ID = T2.GUID  
WHERE (USERNAME = '{0}') AND T2.SHORT_NAME = 'ADDI'", USER_USERNAME)
            LOGGER.Info("Login at: " & Now.ToString)
            LOGGER.Info("Username: " & USER_USERNAME)
            Dim USER_DT As DataTable = MYDB_ECM.GetDatatable(sql)
            If USER_DT.Rows.Count = 0 Then
                LOGGER.Warn(" - User '" & USER_USERNAME & "' not listed in Useradministration!")

                Dim msg = String.Format("You are not listed in the Useradministration." & vbNewLine & "Please contact the admin.")
                MsgBox(msg, MsgBoxStyle.Exclamation)
                ClassHelper.InsertEssential_Log(0, "USER-ID", String.Format("User '{0}' not listed in Userconfiguration", USER_USERNAME))
                Return False
            Else
                Dim Right_RO As Boolean = False
                USER_GUID = USER_DT.Rows(0).Item("GUID")
                USERID_FK_INT_ECM = USER_DT.Rows(0).Item("USERID_FK_INT_ECM")
                USER_WAN = USER_DT.Rows(0).Item("WAN_ENVIRONMENT")
                USER_LANGUAGE = USER_DT.Rows(0).Item("LANGUAGE")
                clsCURRENT.USER_LANGUAGE = USER_LANGUAGE
                USER_DATE_FORMAT = USER_DT.Rows(0).Item("DATE_FORMAT")
                USER_GENERAL_VIEWER = USER_DT.Rows(0).Item("GENERAL_VIEWER")
                Right_RO = True

                Try
                    If CBool(USER_DT.Rows(0).Item("PMO_READ_ONLY")) = True Then
                        WM_READ_ONLY = True
                        LOGGER.Info("WINDREAM IS CONFIGURED READ ONLY!!")
                    End If
                Catch ex As Exception

                End Try


                If Right_RO = False Then
                    LOGGER.Warn("User '" & USER_USERNAME & "' not authorized for using OrgFlow!")
                    'MsgBox("Achtung: Sie sind nicht für die Nutzung dieses Moduls freigeschaltet." & vbNewLine & "Bitte setzen Sie sich mit dem Systembetreuer in Verbindung!", MsgBoxStyle.Critical, "Achtung:")
                    Dim msg = String.Format("Sie sind nicht für die Nutzung dieses Moduls freigeschaltet." & vbNewLine & "Bitte setzen Sie sich mit dem Systembetreuer in Verbindung!")

                    If USER_LANGUAGE <> "de-DE" Then
                        msg = String.Format("You are not authorized for using this module." & vbNewLine & "Please contact the admin.")
                    End If
                    MsgBox(msg, MsgBoxStyle.Exclamation)
                    Return False
                    'Me.Close()
                Else
                    sql = String.Format("select * from TBPMO_RIGHT_USER WHERE USER_ID = " & USER_GUID)
                    CURRENT_TBPMO_RIGHT_USER = MYDB_ECM.GetDatatable(sql)


                    Init_CONN_SWITCH()
                    DT_CLIENT_USER = MYDB_ECM.GetDatatable("SELECT T.*, T1.LICENSE_PMO, T1.CLIENT_NAME FROM TBDD_CLIENT_USER T,TBDD_CLIENT T1 WHERE T.CLIENT_ID = T1.GUID AND T.USER_ID = " & USER_GUID)
                    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")
                    End If
                    If CLIENT_SELECTED = 99 Then
                        Dim msg = String.Format("Die Mandantenanmeldung war nicht möglich." & vbNewLine & "Bitte setzen Sie sich mit dem Systembetreuer in Verbindung!")

                        If USER_LANGUAGE <> "de-DE" Then
                            msg = String.Format("The client-login was not possible." & vbNewLine & "Please contact the admin.")
                        End If
                        MsgBox(msg, MsgBoxStyle.Exclamation)
                        Return False
                    End If

                    'Am System anmelden
                    ClassLicence.Refresh_Licence(CLIENT_SELECTED)
                    'Am System anmelden
                    'sql = String.Format("UPDATE TBDD_USER SET LOGGED_IN = 1, LOGGED_WHERE = '{0}' WHERE GUID = {1}", Environment.MachineName, USER_GUID)
                    MYDB_ECM.ExecuteNonQuery(sql)
                    sql = "DELETE FROM TBDD_USER_MODULE_LOG_IN WHERE USER_ID = " & USER_GUID & " AND UPPER(MODULE)= UPPER('Record-Organizer')"
                    If MYDB_ECM.ExecuteNonQuery(sql) = True Then

                    End If
                    Dim ConStringMain As String
                    If clsDatabase.DB_PROXY_INITIALIZED = True Then
                        ConStringMain = "PROXY: " & ClassProxy.MyPROXYConnectionString & " # MAIN: " & MyConnectionString
                    Else
                        ConStringMain = "Main: " & MyConnectionString
                    End If
                    sql = String.Format("INSERT INTO TBDD_USER_MODULE_LOG_IN (USER_ID,CLIENT_ID,MODULE,VERSION_CLIENT,MACHINE_NAME,CONNECTION_STRING) VALUES ({0},{1},'Record-Organizer','{2}','{3}','{4}')", USER_GUID, CLIENT_SELECTED, My.Application.Info.Version.ToString, Environment.MachineName, ConStringMain)
                    MYDB_ECM.ExecuteNonQuery(sql)

                    USER_IS_ADMIN = USER_DT.Rows(0).Item("IS_ADMIN") 'vorher RECORD_ADMIN
                    If USER_IS_ADMIN = True Then
                        If ESC_Hidden = True Then
                            frmLoginUserSelect.ShowDialog()
                            ESC_Hidden = False
                            If USER_USERNAME <> "" Then
                                InitUserLogin(USER_USERNAME)
                            End If
                        End If
                    Else

                    End If
                    Try
                        If WM_READ_ONLY = True Then
                            If SHARE_DRIVE_ACTIVE = True Then
                                LOGGER.Info($"SHAREDRIVE IS ACTIVE = {SHARE_DRIVE_ACTIVE.ToString}")
                                WM_READ_ONLY = True
                            End If

                        Else
                            Try
                                WMMOD = New DigitalData.Modules.Windream.Windream(LOGCONFIG, False, WMDriveLetter, WMPATH_PREFIX, True, "", "", "", "")
                                If IsNothing(WMMOD) Then
                                    MsgBox("No windream connectable", MsgBoxStyle.Exclamation)
                                End If
                            Catch ex As Exception
                                LOGGER.Warn("Could not create the login for DigitalData.Modules.Windream.Windream!")
                            End Try

                            If clsWindream.Create_Session = False Then
                                LOGGER.Warn("Could not create the login for windream - No session created!")
                                ClassHelper.MSGBOX_Handler("ERROR", "windream-login Error:", "Could not create the login/session!", "OrgFlow will start anyway but be aware that searching and importing won't be possible!")
                            End If
                        End If


                    Catch ex As Exception
                        LOGGER.Warn("Unexpected Error in clswindream.Init: " & ex.Message)
                        MsgBox("Unexpected Error in Creating windream-Session: " & ex.Message & vbNewLine & "Please inform Your sysadmin!", MsgBoxStyle.Critical)
                    End Try

                    sql = String.Format("SELECT COUNT(*) AS Expr1 FROM TBDD_USER_MODULE_LOG_IN WHERE UPPER(MODULE) = UPPER('Record-Organizer') AND CLIENT_ID = {0}", CLIENT_SELECTED)
                    Dim anzahl = MYDB_ECM.GetScalarValue(sql)
                    USERS_LOGGED_IN = CInt(anzahl)
                    LOGGER.Info("User# logged in: " & anzahl.ToString)
                    LOGGER.Info("LICENSE_COUNT: " & LICENSE_COUNT.ToString)
                    '####

                    If LICENSE_COUNT <= (USERS_LOGGED_IN + 1) And LICENSE_EXPIRED = False Then
                        Dim msg = String.Format("Die Anzahl der aktuell angemeldeten User (" & USERS_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!")

                        If USER_LANGUAGE <> "de-DE" Then
                            msg = String.Format("The number of logged Users (" & USERS_LOGGED_IN.ToString & ") exceeds the number of licenses." & vbNewLine &
                                                "Number of licenses: " & LICENSE_COUNT.ToString & vbNewLine & "Please contact Your admin!")
                        End If
                        MsgBox(msg, MsgBoxStyle.Exclamation)
                        LOGGER.Warn("The number of logged Users (" & USERS_LOGGED_IN.ToString & ") exceeds the number of licenses (" & LICENSE_COUNT & ") ")
                        If USER_IS_ADMIN = False Then
                            'Anmeldung wieder herausnehmen
                            sql = "DELETE FROM TBDD_USER_MODULE_LOG_IN WHERE USER_ID = " & USER_GUID & " AND MODULE= 'Record-Organizer'"
                            MYDB_ECM.ExecuteNonQuery(sql)
                            LOGGER.Warn(" - logged out the user")
                            Return False
                        End If
                    Else
                        Try
                            'Die FolderWatch starten
                            Dim sql1 = "SELECT FOLDER_PATH FROM TBPMO_FOLDERWATCH_USER WHERE FOLDER_TYPE = 'SCAN' AND USER_ID = " & USER_GUID
                            Dim folderwatch_SCAN = MYDB_ECM.GetScalarValue(sql1)

                            If Not folderwatch_SCAN Is Nothing Then
                                CURRENT_SCAN_FOLDERWATCH = folderwatch_SCAN
                                If FWSCAN_started = True Then
                                    ClassFolderWatcher.StartStop_FolderWatchSCAN()
                                End If
                            End If
                        Catch ex As Exception
                            LOGGER.Warn("Unexpected Error in Init_Folderwatch: " & ex.Message, True)
                            Return False
                        End Try

                    End If
                    If LICENSE_PROXY = True And clsDatabase.DB_PROXY_INITIALIZED Then
                        SQL_FULLTEXT = "SELECT DISTINCT [dwDocID] FROM [dbo].FullText WHERE CONTAINS([Text], '""*@FULLTEXT*""') "
                    End If
                    Dim oSQL = $"SELECT COUNT(GU.GUID) FROM	TBDD_GROUPS_USER GU INNER JOIN TBDD_GROUPS G ON GU.GROUP_ID = G.GUID WHERE G.NAME = 'ORGFLOW-Supervisor' AND GU.USER_ID = {USER_GUID}"
                    USER_IS_SUPERVISOR = MYDB_ECM.GetScalarValue(oSQL)
                    Return True
                    'LabelLoggedIn.Caption = "Anzahl Angemeldete User: " & anzahl.ToString
                End If
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Warn("Unexpected Error in InitUserLogin: " & ex.Message)
            MsgBox("Unexpected Error in InitUserLogin: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try

    End Function

End Class
