Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Windream
Imports DigitalData.Modules.Messaging
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Base

Public Class ClassInit
    Private Form As Form

    Public Sub New(pForm As Form)
        Form = pForm
    End Sub

    Public Sub InitLogger()
        LOGCONFIG = New LogConfig(LogConfig.PathType.AppData, Nothing, Nothing,
                                  CompanyName:=My.Application.Info.CompanyName,
                                  ProductName:=My.Application.Info.ProductName)
        LOGGER = LOGCONFIG.GetLogger("fileFLOW")
        LOGGER.Info("Programmstart: " & Now)
        LOGGER.Info("Username: {0}", Environment.UserName)
    End Sub

    Public Sub InitConfig()
        Dim oUtils = New ConfigUtils(LOGCONFIG)
        oUtils.MigrateUserAppDataConfig(Application.UserAppDataPath, Application.ProductName, "fileFLOW")
        oUtils.MigrateCommonAppDataConfig(Application.CommonAppDataPath, Application.ProductName, "fileFLOW")
        Dim oCommonAppDataPath = Application.CommonAppDataPath
        Dim oStartupPath = Application.StartupPath
        If My.Settings.UseAppConfig = True Then
            LOGGER.Info("Achtung: Anstatt ComputerConfig wird AppConfig benutzt! (UseAppConfig in Appdata)")
            oCommonAppDataPath = oStartupPath
        End If
        CONFIG = New ConfigManager(Of ClassConfig)(LOGCONFIG, Application.UserAppDataPath, oCommonAppDataPath, Application.StartupPath)

        LOGCONFIG.Debug = CONFIG.Config.LogDEBUG
        LOGGER.Info("Debug log set to: [{0}]", LOGCONFIG.Debug)

        MyConnectionString = DecryptConnectionString(CONFIG.Config.ConnectionString)
        LogErrorsOnly = CONFIG.Config.LogDEBUG

        '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
            ' === NEW ===
            DATABASE_ECM = New MSSQLServer(LOGCONFIG, MyConnectionString)
            dbResult = DATABASE_ECM.DBInitialized

            ' === OLD ===
            '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()

            ' === NEW ===
            DATABASE_ECM = New MSSQLServer(LOGCONFIG, MyConnectionString)
            dbResult = DATABASE_ECM.DBInitialized

            ' === OLD ===
            '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()

        EMAIL = New Email2(LOGCONFIG)
        FILESYSTEM = New FilesystemEx(LOGCONFIG)

        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
        Else
            If IDB_ACTIVE = False Then
                Try
                    WINDREAM = New Windream(LOGCONFIG, False, WMDrive, WINDREAM_BASEPATH, True, "", "", "", "")
                    If Not IsNothing(WINDREAM) Then
                        If WINDREAM.SessionLoggedin = True Then
                            LOGGER.Debug("windream initialisiert")
                        Else
                            Throw New Exception("Could not create a windream session")
                        End If
                    End If
                Catch ex As Exception
                    LOGGER.Warn("CHECKING WMConnectivity: " & ex.Message)
                    Throw New Exception("Unexpected error in CHECKING WMConnectivity")
                End Try
            End If

        End If
    End Sub

    Public Function Load_BasicConfig()
        Try
            'ClassDatabase.Init()
            Dim oSql As String = "SELECT * FROM TBDD_MODULES WHERE NAME = 'fileFLOW'"
            Dim DT As DataTable = DATABASE_ECM.GetDatatable(oSql)

            If DT.Rows.Count = 1 Then
                GI_withWindream = DT.Rows(0).Item("BIT1")
                'vWLaufwerk = DT.Rows(0).Item("STRING1")
            End If
            oSql = "SELECT * FROM TBDD_CATALOG"
            DT = DATABASE_ECM.GetDatatable(oSql)
            For Each oROW As DataRow In DT.Rows
                If oROW.Item("CAT_TITLE") = "WM_DB_SERVER" Then
                    WM_DB_SERVER = oROW.Item("CAT_STRING")
                End If
            Next
            VIEWER_LICENSE = DATABASE_ECM.GetScalarValue($"SELECT LICENSE FROM TBDD_3RD_PARTY_MODULES WHERE 
                    NAME = 'GDPICTURE_FILEFLOW' AND ACTIVE = 1")
            oSql = "SELECT * FROM TBDD_BASECONFIG"
            DT = DATABASE_ECM.GetDatatable(oSql)
            If DT.Rows.Count = 1 Then
                WMDrive = DT.Rows(0).Item("WM_DRIVE")
                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
            FILE_HANDLER = New ClassFileHandler(LOGCONFIG)
            FOLDER_WATCHER = New ClassFolderWatcher(LOGCONFIG)
            AddHandler FOLDER_WATCHER.FileCreated, AddressOf OnCreated

            Dim sql As String = "SELECT FOLDER_PATH FROM TBGI_FOLDERWATCH_USER WHERE FOLDER_TYPE = 'DEFAULT' AND USER_ID = " & USER_ID
            Dim folderwatchPath = DATABASE_ECM.GetScalarValue(sql)

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

            If folderwatchPath = String.Empty Then
                LOGGER.Info("Init_Folderwatch: folderwatchPath is empty")
                FW_started = False
                'SaveConfigValue("FW_started", "False")
                CONFIG.Config.FolderWatchStarted = False
                CONFIG.Save()

            End If

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

            End If

            CURRENT_FOLDERWATCH = folderwatchPath

            FW_started = True
            FWFunction_STARTED = True
            FOLDER_WATCHER.StartStop_FolderWatch()
        Catch ex As Exception
            MsgBox($"Init_Folderwatch: Unexpected error while starting FolderWatch: {ex.Message}", MsgBoxStyle.Critical)
            LOGGER.Info($"Init_Folderwatch: Unexpected error: {ex.Message}")
            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 = DATABASE_ECM.GetScalarValue(sql)

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

            If folderwatchScanPath = String.Empty Then
                LOGGER.Info("Init_Folderwatch: folderwatchScanPath is empty")
                CONFIG.Config.FolderWatchStarted = False
                CONFIG.Save()
                Exit Sub
            End If

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

            CURRENT_SCAN_FOLDERWATCH = folderwatchScanPath


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

    Private Sub OnCreated(source As Object, e As IO.FileSystemEventArgs)
        Try
            For Each row As DataRow In DTEXCLUDE_FILES.Rows
                Dim content As String = row.Item(0).ToString.ToLower
                If e.FullPath.ToLower.Contains(content) Then
                    Exit Sub
                End If
            Next

            Dim oHandleType As String
            If e.FullPath.ToLower.EndsWith(".msg") Then
                oHandleType = "|FW_OUTLOOK_MESSAGE|"
            Else
                oHandleType = "|FW_SIMPLEINDEXER|"
            End If
            'Die Datei übergeben
            LOGGER.Info(">> Adding file from Hotfolder (OnCreated):" & e.FullPath)
            If ClassIndexFunctions.CheckDuplicateFiles(Form, e.FullPath, "FolderWatch/Scan") Then
                FILE_HANDLER.Decide_FileHandle(e.FullPath, oHandleType)
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in folder_watch_Created")
        End Try

    End Sub

    Public Sub InitUserLogin()
        Try
            Dim oSql As String

            oSql = String.Format($"SELECT * FROM [dbo].[FNDD_LOGIN_USER_MODULE] ('{Environment.UserName}','fileFLOW',{1})")
            Dim DT_CHECKUSER_MODULE As DataTable = DATABASE_ECM.GetDatatable(oSql)
            If DT_CHECKUSER_MODULE.Rows.Count = 0 Then
                LOGGER.Info("DT_CHECKUSER_MODULE.Rows.Count = 0")
                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

                Dim oRow As DataRow = DT_CHECKUSER_MODULE.Rows(0)

                If oRow.Item("USER_ID") = 0 And IsDBNull(oRow.Item("USER_SURNAME")) Then
                    LOGGER.Info("User '" & Environment.UserName & "' not configured in Useradministration!")
                    START_INCOMPLETE = True
                    Throw New Exception("You are not configured in the Useradministration." & vbNewLine & "Please contact the system administrator!")
                    Exit Sub
                End If
                USER_IN_MODULE = oRow.Item("MODULE_ACCESS")
                USER_ID = oRow.Item("USER_ID")
                USER_SURNAME = IIf(IsDBNull(oRow.Item("USER_SURNAME")), "", oRow.Item("USER_SURNAME"))
                USER_PRENAME = IIf(IsDBNull(oRow.Item("USER_PRENAME")), "", oRow.Item("USER_PRENAME"))
                USER_SHORTNAME = IIf(IsDBNull(oRow.Item("USER_SHORTNAME")), "", oRow.Item("USER_SHORTNAME"))
                USER_EMAIL = IIf(IsDBNull(oRow.Item("USER_EMAIL")), "", oRow.Item("USER_EMAIL"))
                USER_LANGUAGE = oRow.Item("USER_LANGUAGE")
                USER_IN_MODULE = oRow.Item("MODULE_ACCESS")
                USER_IS_ADMIN = oRow.Item("IS_ADMIN")
                USERCOUNT_LOGGED_IN = oRow.Item("USERCOUNT_LOGGED_IN")
                ClassParamRefresh.Refresh_Params(DT_CHECKUSER_MODULE)
                If USER_IN_MODULE = False Then
                    LOGGER.Info(" - User: " & Environment.UserName & " nicht für Modul freigegben!")
                    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 = oRow.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 = DATABASE_ECM.GetScalarValue(sql1)
                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 = oRow.Item("USER_LANGUAGE")

                oSql = "DELETE FROM TBDD_USER_MODULE_LOG_IN WHERE USER_ID = " & USER_ID & " AND MODULE = 'fileFLOW'"
                DATABASE_ECM.ExecuteNonQuery(oSql)
                oSql = "INSERT INTO TBDD_USER_MODULE_LOG_IN (USER_ID,MODULE, CLIENT_ID) VALUES (" & USER_ID & ",'fileFLOW', 1)"
                DATABASE_ECM.ExecuteNonQuery(oSql)
                oSql = "SELECT COUNT(*) AS Expr1 FROM TBDD_USER_MODULE_LOG_IN WHERE MODULE = 'fileFLOW'"

                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 fileFLOW!")
                    If USER_IS_ADMIN = False Then
                        'Anmeldung wieder herausnehmen
                        oSql = "DELETE FROM TBDD_USER_MODULE_LOG_IN WHERE USER_ID = " & USER_ID & " AND MODULE = 'fileFLOW'"
                        DATABASE_ECM.ExecuteNonQuery(oSql)
                        LOGGER.Info(" - Wieder abgemeldet")
                        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
            LOGGER.Info("Unexpected Error in InitUserLogin: " & ex.Message)
            LOGGER.Error(ex)
            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
