Imports System.ComponentModel
Imports System.IO
Imports DD_LIB_Standards
Public Class ClassInit
    Public Sub New()
    End Sub

    Public Sub InitLogger()
        ClassLogger.Init("", USER_USERNAME)
        clsLogger.LOGFILE_PATH = ClassLogger.logDateiname
    End Sub

    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 MyConnectionString <> String.Empty Then
                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")
                End If
            End If
            ClassDatabase.Init()
            If dbResult = 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
            Return True
        Catch ex As Exception
            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 Sql As String = "SELECT PATH_ADDONS from TBPMO_KONFIGURATION WHERE GUID = 1"
            Dim AddonPath As String = MY_ADDON_PATH ' ClassDatabase.Execute_Scalar(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
            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 = ClassDatabase.Return_Datatable(sql, False)
            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")
            End If

            sql = "SELECT * FROM TBPMO_CONTROL"
            CURRENT_TBPMO_CONTROL = ClassDatabase.Return_Datatable(sql, True)
        Catch ex As Exception
            MsgBox("Unexpected Error in InitBasics2:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        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 * FROM TBDD_USER WHERE (LOWER(USERNAME) = LOWER('{0}'))", USER_USERNAME)
            ClassLogger.Add(">> Login at: " & Now.ToString, False)
            ClassLogger.Add(">> Username: " & USER_USERNAME, False)
            Dim USER_DT As DataTable = ClassDatabase.Return_Datatable(sql, True)
            If USER_DT.Rows.Count = 0 Then
                ClassLogger.Add(" - User '" & USER_USERNAME & "' not listed in Useradminsitration!", False)
                'MsgBox("Achtung: Sie sind nicht in der Userverwaltung hinterlegt." & vbNewLine & "Bitte setzen Sie sich mit dem Systembetreuer in Verbindung!", MsgBoxStyle.Critical, "Achtung:")
                'Me.Close()
                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") 'ClassDatabase.Execute_Scalar("SELECT WAN_ENVIRONMENT FROM TBDD_USER WHERE GUID = " & USER_GUID, False)
                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")
                sql = String.Format("SELECT COUNT(T.GUID) FROM TBDD_USER_MODULES T, TBDD_MODULES T1 WHERE T.MODULE_ID = T1.GUID AND T1.NAME = 'Record-Organizer' AND T.USER_ID = {0}", USER_GUID)
                Dim USER2MODULE = clsDatabase.Execute_Scalar(sql)
                If Not IsNothing(USER2MODULE) Then
                    If USER2MODULE = 1 Then
                        Right_RO = True
                    End If
                Else
                    Right_RO = USER_DT.Rows(0).Item("MODULE_RECORD_ORG")
                End If
           

                If Right_RO = False Then
                    ClassLogger.Add("User '" & USER_USERNAME & "' not authorized for using Record-Organizer!")
                    '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
                    'USER_LANGUAGE = ClassDatabase.Execute_Scalar("SELECT LANGUAGE FROM TBDD_USER WHERE GUID = " & USER_GUID, False)
                    DT_CLIENT_USER = ClassDatabase.Return_Datatable("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, False)
                    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)
                    ClassDatabase.Execute_non_Query(sql)
                    sql = "DELETE FROM TBDD_USER_MODULE_LOG_IN WHERE USER_ID = " & USER_GUID & " AND UPPER(MODULE)= UPPER('Record-Organizer')"
                    If ClassDatabase.Execute_non_Query(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)
                    ClassDatabase.Execute_non_Query(sql)

                    USER_IS_ADMIN = USER_DT.Rows(0).Item("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 clsWindream.Create_Session = False Then
                            ClassLogger.Add("Could not create the login for windream - No session created!")
                            ClassHelper.MSGBOX_Handler("ERROR", "windream-login Error:", "Could not create the login/session!", "ADDI will start anyway but be aware that searching and importing won't be possible!")
                        End If
                    Catch ex As Exception
                        ClassLogger.Add("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 = ClassDatabase.Execute_Scalar(sql, False)
                    USERS_LOGGED_IN = CInt(anzahl)
                    If LogErrorsOnly = False Then ClassLogger.Add(" >> User# logged in: " & anzahl.ToString, False)
                    '####

                    If LICENSE_COUNT < USERS_LOGGED_IN 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)
                        ClassLogger.Add(" >> The number of logged Users (" & USERS_LOGGED_IN.ToString & ") exceeds the number of licenses (" & LICENSE_COUNT & ") ", False)
                        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'"
                            ClassDatabase.Execute_non_Query(sql)
                            ClassLogger.Add(" - logged out the user", False)
                            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 = ClassDatabase.Execute_Scalar(sql1, False)

                            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
                            ClassLogger.Add("Unexpected Error in Init_Folderwatch: " & ex.Message, True)
                            Return False
                        End Try

                    End If
                    If LICENSE_SITE_PROXY = True And clsDatabase.DB_PROXY_INITIALIZED Then
                        SQL_FULLTEXT = "SELECT DISTINCT [dwDocID] FROM [dbo].FullText WHERE CONTAINS([Text], '""*@FULLTEXT*""')"
                    End If
                    Return True
                    'LabelLoggedIn.Caption = "Anzahl Angemeldete User: " & anzahl.ToString
                    End If
            End If
        Catch ex As Exception
            ClassLogger.Add("Unexpected Error in InitUserLogin: " & ex.Message)
            MsgBox("Unexpected Error in InitUserLogin: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try

    End Function

End Class
