Imports System.ComponentModel
Imports DLLLicenseManager
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Config

Public Class ClassInit
    Public _lizenzManager As ClassLicenseManager
    Public Sub New()
    End Sub

    Public Sub InitLogger()
        ClassLogger.Init("", Environment.UserName)
        ClassLogger.Add(">> Programmstart: " & Now, False)
        ClassLogger.Add(">> Username: " & Environment.UserName, False)
        LOGCONFIG = New LogConfig(LogConfig.PathType.AppData)
        LOGGER = LOGCONFIG.GetLogger("Globix")
        LOGGER.Info("Username: {0}", Environment.UserName)
    End Sub

    Public Sub InitConfig()
        CONFIG = New ConfigManager(Of ClassConfig)(LOGCONFIG, Application.UserAppDataPath, Application.CommonAppDataPath)

        MyConnectionString = DecryptConnectionString(CONFIG.Config.ConnectionString)
        LogErrorsOnly = CONFIG.Config.LogErrorsOnly
        'myPreviewActive = CONFIG.Config.FilePreview
        FW_started = CONFIG.Config.FolderWatchStarted
        CURR_DELETE_ORIGIN = CONFIG.Config.DeleteOriginalFile
    End Sub

    Public Function InitDatabase()
        Dim dbResult As Boolean
        'LoadMyConfig()
        If LoadFileExclusion() = False Then
            If USER_LANGUAGE = "de-DE" Then
                MsgBox("Die Ausschlusskriterien für Dateien in Folderwatch konnten nicht angelegt werden!", MsgBoxStyle.Information)
            Else
                MsgBox("File-Exclusions in Folderwatch could not be created!", MsgBoxStyle.Information)
            End If

        End If

        If MyConnectionString <> String.Empty Then
            dbResult = ClassDatabase.Init()
        Else
            MsgBox("No Databaseconnection configured. (First Start or Appdata not accessible)" & vbNewLine & "Basic-Config will be loaded.", MsgBoxStyle.Information)
            ERROR_STATE = "NO DB-CONNECTION"
            frmConfig_Basic.ShowDialog()
            dbResult = ClassDatabase.Init()
        End If

        If dbResult = False Then
            ERROR_STATE = "FAILED DBCONNECTION"
            ' Fehler wird in frmSplash abgehandelt
            'MsgBox("Error in init database. (Connection failed) More information in the logfile.", MsgBoxStyle.Critical)
            Return False
        Else
            Return True
        End If
    End Function
    <STAThread()>
    Public Sub InitBasics()
        Dim configResult As Boolean
        configResult = Load_BasicConfig()

        If configResult = False Then
            If USER_LANGUAGE = "de-DE" Then
                Throw New Exception("Unerwarteter Fehler beim Initialisieren der Basis-Einstellungen. Weitere Informationen finden Sie in der Logdatei.")
            Else
                Throw New Exception("Unexpected error while initializing basic-settings. More info in the log.")
            End If
        End If
    End Sub

    Public Function Load_BasicConfig()
        Try
            ClassDatabase.Init()
            Dim oSql As String = "select * from tbdd_Modules where NAME = 'Global-Indexer'"
            Dim DT As DataTable = ClassDatabase.Return_Datatable(oSql)
            If DT.Rows.Count = 1 Then
                GI_withWindream = DT.Rows(0).Item("BIT1")
                vWLaufwerk = DT.Rows(0).Item("STRING1")

                DTTBGI_REGEX_DOCTYPE = ClassDatabase.Return_Datatable("SELECT T1.DOCTYPE as DocType, T.* FROM TBGI_REGEX_DOCTYPE T, VWGI_DOCTYPE T1 WHERE T.DOCTYPE_ID = T1.DOCTYPE_ID")
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            MsgBox("Error in Load_BasicConfig" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
        Return True
    End Function

    Public Sub Init_Folderwatch()
        Try
            Dim sql As String = "SELECT FOLDER_PATH FROM TBGI_FOLDERWATCH_USER WHERE FOLDER_TYPE = 'DEFAULT' AND USER_ID = " & USER_ID
            Dim folderwatchPath = ClassDatabase.Execute_Scalar(sql, MyConnectionString, True)

            folderwatchPath = IIf(IsDBNull(folderwatchPath), "", folderwatchPath)

            If folderwatchPath = String.Empty Then
                ClassLogger.Add("Init_Folderwatch: folderwatchPath is empty", True)
                FW_started = False
                'SaveConfigValue("FW_started", "False")
                CONFIG.Config.FolderWatchStarted = False
                CONFIG.Save()
     
            End If

            If Not IO.Directory.Exists(folderwatchPath) Then
                ClassLogger.Add("Init_Folderwatch: folderwatchPath does not exists or is invalid path", True)
                FW_started = False
                'SaveConfigValue("FW_started", "False")
                CONFIG.Config.FolderWatchStarted = False
                CONFIG.Save()
               
            End If

            CURRENT_FOLDERWATCH = folderwatchPath

            FW_started = True
            FWFunction_STARTED = True
            ClassFolderWatcher.StartStop_FolderWatch()
        Catch ex As Exception
            MsgBox($"Init_Folderwatch: Unexpected error while starting FolderWatch: {ex.Message}", MsgBoxStyle.Critical)
            ClassLogger.Add($"Init_Folderwatch: Unexpected error: {ex.Message}", True)
            START_INCOMPLETE = True
        End Try

        Try
            Dim sql As String = "SELECT FOLDER_PATH FROM TBGI_FOLDERWATCH_USER WHERE FOLDER_TYPE = 'SCAN' AND USER_ID = " & USER_ID
            Dim folderwatchScanPath = ClassDatabase.Execute_Scalar(sql, MyConnectionString, True)

            folderwatchScanPath = IIf(IsDBNull(folderwatchScanPath), "", folderwatchScanPath)

            If folderwatchScanPath = String.Empty Then
                ClassLogger.Add("Init_Folderwatch: folderwatchScanPath is empty", True)
                CONFIG.Config.FolderWatchStarted = False
                CONFIG.Save()
                Exit Sub
            End If

            If Not IO.Directory.Exists(folderwatchScanPath) Then
                ClassLogger.Add("Init_Folderwatch: folderwatchScanPath does not exists or is invalid path", True)
                CONFIG.Config.FolderWatchStarted = False
                CONFIG.Save()
                Exit Sub
            End If

            CURRENT_SCAN_FOLDERWATCH = folderwatchScanPath


            FWFunction_STARTED = True
            ClassFolderWatcher.StartStop_FolderWatchSCAN()
        Catch ex As Exception
            MsgBox($"Init_Folderwatch: Unexpected error while starting FolderWatchScan: {ex.Message}", MsgBoxStyle.Critical)
            ClassLogger.Add($"Init_Folderwatch: Unexpected error: {ex.Message}", True)
            START_INCOMPLETE = True
        End Try



        'Try
        '    'Die FolderWatch starten
        'Dim sql1 = "SELECT FOLDER_PATH FROM TBGI_FOLDERWATCH_USER WHERE FOLDER_TYPE = 'DEFAULT' AND USER_ID = " & CURRENT_USER_ID
        '    Dim folderwatch = ClassDatabase.Execute_Scalar(sql1, MyConnectionString, True)
        '    sql1 = "SELECT FOLDER_PATH FROM TBGI_FOLDERWATCH_USER WHERE FOLDER_TYPE = 'SCAN' AND USER_ID = " & CURRENT_USER_ID
        '    Dim folderwatch_SCAN = ClassDatabase.Execute_Scalar(sql1, MyConnectionString, True)
        '    If Not folderwatch Is Nothing Then
        '        CURRENT_FOLDERWATCH = folderwatch
        '        If FW_started = True Then
        '            If CURRENT_FOLDERWATCH = "" Then
        '                FW_started = False
        '                SaveConfigValue("FW_started", "False")
        '            Else
        '                FW_ISSTARTED = True
        '                ClassFolderWatcher.StartStop_FolderWatch()
        '            End If

        '        End If
        '    Else
        '        ClassLogger.Add("Init_Folderwatch: folderwatch path is nothing!", True)
        '    End If
        '    If Not folderwatch_SCAN Is Nothing Then
        '        CURRENT_SCAN_FOLDERWATCH = folderwatch_SCAN
        '        If FWSCAN_started = True Then
        '            FW_ISSTARTED = True
        '            ClassFolderWatcher.StartStop_FolderWatchSCAN()
        '        End If
        '    Else
        '        ClassLogger.Add("Init_Folderwatch: folderwatch_SCAN path is nothing!", True)
        '    End If
        'Catch ex As Exception
        '    ClassLogger.Add("Unexpected Error in Init_Folderwatch: " & ex.Message, True)
        '    START_INCOMPLETE = True
        'End Try
    End Sub
    Public Sub InitUserLogin()
        Try
            Dim sql = "SELECT MAX(GUID) FROM TBDD_USER WHERE (LOWER(USERNAME) = LOWER('@user'))"
            sql = sql.Replace("@user", Environment.UserName)
            ' ClassLogger.Add(">> Username: " & Environment.UserName, False)

            USER_ID = ClassDatabase.Execute_Scalar(sql, MyConnectionString, True)
            Try
                Dim USERID = CInt(USER_ID)
            Catch ex As Exception
                ClassLogger.Add("User '" & Environment.UserName & "' not configured in Useradministration! (DBNull)", True)
                'MsgBox("Achtung: Sie sind nicht in der Userverwaltung hinterlegt." & vbNewLine & "Bitte setzen Sie sich mit dem Systembetreuer in Verbindung!", MsgBoxStyle.Critical, "Achtung:")
                'Me.Close()
                START_INCOMPLETE = True
                Throw New Exception("You are not configured in the Useradministration." & vbNewLine & "Please contact the system administrator!")
                Exit Sub
            End Try

            Dim oUserDatatable As DataTable = ClassDatabase.Return_Datatable($"SELECT * FROM TBDD_USER WHERE GUID = {USER_ID}")
            If Not IsNothing(oUserDatatable) AndAlso Not IsDBNull(oUserDatatable.Rows.Item(0)) Then
                Dim oRow As DataRow = oUserDatatable.Rows.Item(0)
                USER_SHORT_NAME = NotNull(oRow.Item("SHORTNAME"), String.Empty)
                USER_PRENAME = NotNull(oRow.Item("PRENAME"), String.Empty)
                USER_SURNAME = NotNull(oRow.Item("NAME"), String.Empty)
                USER_EMAIL = NotNull(oRow.Item("EMAIL"), String.Empty)
                USER_USERNAME = NotNull(oRow.Item("USERNAME"), String.Empty)
            End If

            'Check_User_Exists_in_GIGroups()
            sql = String.Format("SELECT * FROM [dbo].[FNDD_CHECK_USER_MODULE] ('{0}','GLOBIX',{1})", Environment.UserName, 1)
            Dim DT_CHECKUSER_MODULE As DataTable = ClassDatabase.Return_Datatable(sql)
            If DT_CHECKUSER_MODULE.Rows.Count = 0 Then
                ClassLogger.Add("DT_CHECKUSER_MODULE.Rows.Count = 0", True)
                START_INCOMPLETE = 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
                USER_IN_MODULE = DT_CHECKUSER_MODULE.Rows(0).Item("MODULE_ACCESS")
                If USER_IN_MODULE = False Then
                    ClassLogger.Add(" - User: " & Environment.UserName & " nicht für Modul freigegben!", False)
                    START_INCOMPLETE = True

                    Throw New Exception("Your user is not allowed to use this module." & vbNewLine & "Please contact the system administrator!")

                    Exit Sub
                End If
                USER_IS_ADMIN = DT_CHECKUSER_MODULE.Rows(0).Item("IS_ADMIN")

                ClassLicence.Refresh_Licence()

                Dim sql1 = "SELECT COUNT(T.GUID) FROM TBDD_DOKUMENTART T, TBDD_DOKUMENTART_MODULE T1 WHERE T.AKTIV = 1 AND T.GUID = T1.DOKART_ID AND T1.MODULE_ID = 1"
                DOCTYPE_COUNT_ACTUAL = ClassDatabase.Execute_Scalar(sql1, MyConnectionString, True)
                If DOCTYPE_COUNT_ACTUAL > LICENSE_DOCTYPE_COUNT Then
                    If USER_LANGUAGE = "de-DE" Then
                        MsgBox("Ihre Anzahl von konfigurierbaren Dokumentarten ist limitiert auf: '" & LICENSE_DOCTYPE_COUNT.ToString & "'." & vbNewLine & "Bitte kontaktieren Sie Digital Data für weitere Details.", MsgBoxStyle.Information)
                    Else
                        MsgBox("Your amount of configurable documenttypes is limited to " & LICENSE_DOCTYPE_COUNT.ToString & " doctypes. You can not add more doctypes!" & vbNewLine & "Please contact Digital Data for further licensedetails", MsgBoxStyle.Information)
                    End If
                End If
                USER_LANGUAGE = DT_CHECKUSER_MODULE.Rows(0).Item("USER_LANGUAGE")

                sql = "DELETE FROM TBDD_USER_MODULE_LOG_IN WHERE USER_ID = " & USER_ID & " AND UPPER(MODULE) = UPPER('Global-Indexer')"
                ClassDatabase.Execute_non_Query(sql, True)
                sql = "INSERT INTO TBDD_USER_MODULE_LOG_IN (USER_ID,MODULE) VALUES (" & USER_ID & ",'Global-Indexer')"
                ClassDatabase.Execute_non_Query(sql)
                sql = "SELECT COUNT(*) AS Expr1 FROM TBDD_USER_MODULE_LOG_IN WHERE Upper(MODULE) = UPPER('Global-Indexer')"
                Dim anzahl = ClassDatabase.Execute_Scalar(sql, MyConnectionString, True)
                If LogErrorsOnly = False Then ClassLogger.Add(" >> Anzahl Angemeldete User: " & anzahl.ToString, False)
                UserLoggedin = CInt(anzahl)
                UserLoggedin += 1
                If LICENSE_COUNT < UserLoggedin And LICENSE_EXPIRED = False Then
                    MsgBox("Die Anzahl der aktuell angemeldeten User (" & UserLoggedin.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:")
                    ClassLogger.Add(" >> Die Anzahl der aktuell angemeldeten User (" & UserLoggedin.ToString & ") überschreitet die Anzahl der Lizenzen (" & LICENSE_COUNT & ") für Global Indexer!", False)
                    If USER_IS_ADMIN = False Then
                        'Anmeldung wieder herausnehmen
                        sql = "DELETE FROM TBDD_USER_MODULE_LOG_IN WHERE USER_ID = " & USER_ID & " AND MODULE= 'Global-Indexer'"
                        ClassDatabase.Execute_non_Query(sql, True)
                        ClassLogger.Add(" - Wieder abgemeldet", False)
                        START_INCOMPLETE = True
                    End If
                End If
                'Alles OK bis hierhin...nun die FolderwatchKonfig laden
                Init_Folderwatch()
                'LabelLoggedIn.Caption = "Anzahl Angemeldete User: " & anzahl.ToString
            End If


        Catch ex As Exception
            ClassLogger.Add("Unexpected Error in InitUserLogin: " & ex.Message, True)
            MsgBox(ex.Message, MsgBoxStyle.Critical)
            START_INCOMPLETE = True
        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

End Class
