Imports System.IO
Imports System.Xml
Imports DD_LIB_Standards
Imports DevExpress.LookAndFeel
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Windream

Module ModuleMySettings
    Public PATH_FileExclusions As String = Path.Combine(Application.UserAppDataPath(), "FileExclusions.xml")
    Dim ConfigPath As String = Path.Combine(Application.UserAppDataPath(), "UserConfig2.xml")

    Public MyConnectionString As String = ""
    Public MyFormsDesign As String = ""

    Public DEBUG As Boolean = False
    Public Sett_TaskOverviewKeepInFront As Boolean = True
    Public Task_Popup_minutes As Integer = 2
    Public Sett_ConstructorStart As Integer
    Public MY_ADDON_PATH As String
    Public MY_WIKISTRING As String
    Public WD_GROUP1 As String
    Public WD_UNICODE As Boolean = False
    Public WMDriveLetter As String
    Public WMPATH_PREFIX As String
    Public WMMOD As Windream
    Public SHARE_DRIVE_ACTIVE As Boolean = False
    Public WM_READ_ONLY As Boolean = False
    Public GridDocResult_BestFitColumns As Boolean = True
    Public SQL_FULLTEXT As String
    Public CAPTION_CONFIRMATION As String = "Bestätigung"
    'Public WD_ShowEnitityDocs As Boolean = True
    Public WD_ShowDocs As Boolean = False

    Public WD_IndexDeleteDocs As Boolean = False

    Public CURRENT_FILE As String = ""

    Public vWLaufwerk As String = "W"
    Public vVERSION_DELIMITER As String = "~"
    Public vFILE_DELIMITER As String = "_"
    Public AUTO_LOGOUT_USER As Integer
    Public DBVERSION As String

    Public USER_IS_ADMIN = False
    Public USER_IS_SUPERVISOR = False
    Public USERS_LOGGED_IN = 0

    Public USER_USERNAME As String
    Public USER_PERSONIFIED_TEST As Boolean = False
    Public USER_GUID = 0
    Public USERID_FK_INT_ECM = 0
    Public USER_LANGUAGE As String = "de-DE"
    Public USER_DATE_FORMAT As String
    Public USER_GENERAL_VIEWER As String
    Public USER_WAN As Boolean = False

    Public DT_CLIENT_USER As DataTable
    Public CLIENT_SELECTED As Integer = 99

    'Public USER_CLIENTS_COMMA_SEPERATED As String
    Public FWSCAN_started As Boolean = False

    Public LOGCONFIG As LogConfig
    Public LOGGER As Logger

    Dim rowresult As String = ""
    Public Function LoadFileExclusion()
        Dim rowresult As String = ""
        Try
            'if file doesn't exist, create the file with its default xml table
            If Not File.Exists(PATH_FileExclusions) Then
                DTEXCLUDE_FILES = CreateExclusionTable()
                DTEXCLUDE_FILES.WriteXml(PATH_FileExclusions)
            End If
            DTEXCLUDE_FILES = GetTablefromXML(PATH_FileExclusions)

            'For Each Row As DataRow In DT.Rows
            '    rowresult &= Row.Item("FILE_CONTAIN")
            '    Select Case Row.Item("FILE_CONTAIN")

            '    End Select

            'Next
            Return True
        Catch ex As Exception
            MsgBox("Error in LoadFileExclusion" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
        Return True

    End Function
    Private Function CreateExclusionTable() As DataTable
        Try
            ' Create sample Customers table, in order
            ' to demonstrate the behavior of the DataTableReader.
            Dim table As New DataTable
            table.TableName = "TBEXCLUSION"

            ' Create two columns, ID and Name.
            table.Columns.Add("FILE_CONTAIN", GetType(System.String))
            Dim newRow As DataRow = table.NewRow()
            newRow("FILE_CONTAIN") = "Thumbs"
            table.Rows.Add(newRow)
            Dim newRow1 As DataRow = table.NewRow()
            newRow1("FILE_CONTAIN") = "\~$"
            table.Rows.Add(newRow1)
            Dim newRow2 As DataRow = table.NewRow()
            newRow2("FILE_CONTAIN") = ".db"
            table.Rows.Add(newRow2)
            Dim newRow3 As DataRow = table.NewRow()
            newRow3("FILE_CONTAIN") = "desktop.ini"
            table.Rows.Add(newRow3)
            table.AcceptChanges()
            Return table
        Catch ex As Exception
            MsgBox("Error in CreateExclusionTable" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return Nothing
        End Try
    End Function
    Public Function MySettings_Load()
        Try
            Dim DT As DataTable
            'if file doesn't exist, create the file with its default xml table
            If Not File.Exists(ConfigPath) Then
                LOGGER.Info("ConfigFile was created in: " & ConfigPath)
                DT = CreateConfigTable()
                DT.WriteXml(ConfigPath)
                LOGGER.Info("Defaultvalues were saved.")
            End If
            DT = GetTablefromXML(ConfigPath)
            If DT Is Nothing Then
                MsgBox("Configuration could not be loaded!! Check LogFile!", MsgBoxStyle.Critical)
                Return False
            End If
            For Each Row As DataRow In DT.Rows
                rowresult &= Row.Item("ConfigName")
                Select Case Row.Item("ConfigName")
                    Case "MyConnectionString"
                        Dim connstring As String
                        ''Den ConnectonString mit verschlüsseltem PW laden
                        Dim csb As New SqlClient.SqlConnectionStringBuilder
                        csb.ConnectionString = Row.Item("Value")
                        'If Not csb.ConnectionString = "" Then
                        '    If csb.ConnectionString.Contains("Password=") Then
                        '        'sa-
                        '        'Jetzt das Passwort entschlüsseln
                        '        Dim PWplainText As String
                        '        Dim wrapper As New ClassEncryption("!35452didalog=")
                        '        ' DecryptData throws if the wrong password is used.
                        '        Try
                        '            PWplainText = wrapper.DecryptData(csb.Password)
                        '            connstring = Row.Item("Value").ToString.Replace(csb.Password, PWplainText)
                        '        Catch ex As Exception
                        '            LOGGER.Warn("- the Password '" & csb.Password & "' could not be decrypted")
                        '            connstring = ""
                        '        End Try

                        '    Else
                        '        'Windows-Auth
                        '        connstring = Row.Item("Value").ToString
                        '    End If

                        '    MyConnectionString = connstring
                        'Else
                        '    MyConnectionString = ""
                        'End If
                    Case "MyProxyConnectionString"
                        Dim connstring As String
                        'Den ConnectonString mit verschlüsseltem PW laden
                        Dim csb As New SqlClient.SqlConnectionStringBuilder
                        csb.ConnectionString = Row.Item("Value")
                        If Not csb.ConnectionString = "" Then
                            If csb.ConnectionString.Contains("Password=") Then
                                'sa-
                                'Jetzt das Passwort entschlüsseln
                                Dim PWplainText As String
                                Dim wrapper As New ClassEncryption("!35452didalog=")
                                ' DecryptData throws if the wrong password is used.
                                Try
                                    PWplainText = wrapper.DecryptData(csb.Password)
                                    connstring = Row.Item("Value").ToString.Replace(csb.Password, PWplainText)
                                Catch ex As Exception
                                    LOGGER.Warn("- the Password '" & csb.Password & "' could not be decrypted")
                                    connstring = ""
                                End Try

                            Else
                                'Windows-Auth
                                connstring = Row.Item("Value").ToString
                            End If

                            ClassProxy.MyPROXYConnectionString = connstring
                        Else
                            ClassProxy.MyPROXYConnectionString = ""
                        End If
                    Case "MyLinkedServer"
                        ClassProxy.MyLinkedServer = Row.Item("Value")
                    Case "LogErrorsOnly"
                        DEBUG = CBool(Row.Item("Value"))
                        clsCURRENT.LOG_ERRORS_ONLY = DEBUG
                        LOGCONFIG.Debug = DEBUG
                    Case "Sett_TaskOverviewKeepInFront"
                        Sett_TaskOverviewKeepInFront = CBool(Row.Item("Value"))
                    Case "WD_IndexDeleteDocs"
                        WD_IndexDeleteDocs = CBool(Row.Item("Value"))
                    Case "WD_ShowDocs"
                        WD_ShowDocs = CBool(Row.Item("Value"))
                    Case "Sett_ConstructorStart"
                        Sett_ConstructorStart = CInt(Row.Item("Value"))
                    Case "FWSCAN_started"
                        FWSCAN_started = CBool(Row.Item("Value"))
                    Case "Task_Popup_minutes"
                        If Row.Item("Value") = String.Empty Then
                            Task_Popup_minutes = 2
                        Else
                            Task_Popup_minutes = CInt(Row.Item("Value"))
                        End If
                    Case "PATH_ADDON"
                        If Row.Item("Value") = String.Empty Then
                            MY_ADDON_PATH = ""
                        Else
                            MY_ADDON_PATH = Row.Item("Value")
                        End If
                    Case "MyFormsDesign"
                        If Row.Item("Value") <> String.Empty Then
                            MyFormsDesign = Row.Item("Value")
                        End If
                    Case "GridDocResult_BestFitColumns"
                        GridDocResult_BestFitColumns = CBool(Row.Item("Value"))

                End Select
            Next
            'update 1.1
            If rowresult.Contains("WD_ShowDocs") = False Then
                Dim newRow As DataRow = DT.NewRow()
                newRow("ConfigName") = "WD_ShowDocs"
                newRow("Value") = "False"
                DT.Rows.Add(newRow)
                DT.WriteXml(ConfigPath)
            End If
            If rowresult.Contains("Sett_ConstructorStart") = False Then
                Dim newRow As DataRow = DT.NewRow()
                newRow("ConfigName") = "Sett_ConstructorStart"
                newRow("Value") = "0"
                DT.Rows.Add(newRow)
                DT.WriteXml(ConfigPath)
            End If
            If rowresult.Contains("FWSCAN_started") = False Then
                Dim newRow As DataRow = DT.NewRow()
                newRow("ConfigName") = "FWSCAN_started"
                newRow("Value") = "False"
                DT.Rows.Add(newRow)
                DT.WriteXml(ConfigPath)
            End If
            If rowresult.Contains("Task_Popup_minutes") = False Then
                Dim newRow As DataRow = DT.NewRow()
                newRow("ConfigName") = "Task_Popup_minutes"
                newRow("Value") = "2"
                DT.Rows.Add(newRow)
                DT.WriteXml(ConfigPath)
            End If
            If rowresult.Contains("PATH_ADDON") = False Then
                Dim newRow As DataRow = DT.NewRow()
                newRow("ConfigName") = "PATH_ADDON"
                newRow("Value") = ""
                DT.Rows.Add(newRow)
                DT.WriteXml(ConfigPath)
            End If
            If rowresult.Contains("MyProxyConnectionString") = False Then
                Dim newRow As DataRow = DT.NewRow()
                newRow("ConfigName") = "MyProxyConnectionString"
                newRow("Value") = ""
                DT.Rows.Add(newRow)
                DT.WriteXml(ConfigPath)
            End If
            If rowresult.Contains("MyLinkedServer") = False Then
                Dim newRow As DataRow = DT.NewRow()
                newRow("ConfigName") = "MyLinkedServer"
                newRow("Value") = ""
                DT.Rows.Add(newRow)
                DT.WriteXml(ConfigPath)
            End If
            If rowresult.Contains("MyFormsDesign") = False Then
                Dim newRow As DataRow = DT.NewRow()
                newRow("ConfigName") = "MyFormsDesign"
                newRow("Value") = ""
                DT.Rows.Add(newRow)
                DT.WriteXml(ConfigPath)
            End If
            If rowresult.Contains("GridDocResult_BestFitColumns") = False Then
                Dim newRow As DataRow = DT.NewRow()
                newRow("ConfigName") = "GridDocResult_BestFitColumns"
                newRow("Value") = "True"
                DT.Rows.Add(newRow)
                DT.WriteXml(ConfigPath)
            End If


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

    End Function
    Private Function GetTablefromXML(path As String)
        Try
            Dim DS As New DataSet
            DS.ReadXml(path)
            Return DS.Tables(0)
        Catch ex As Exception
            MsgBox("Error in GetTablefromXML" & vbNewLine & ex.Message & vbNewLine & "ConfigPath: " & vbNewLine & path, MsgBoxStyle.Critical)
            LOGGER.Warn("Error in GetTablefromXML: " & ex.Message, True)
            LOGGER.Warn("ConfigPath: " & ConfigPath)
            LOGGER.Error(ex)
            Return Nothing
        End Try

    End Function

    Private Function CreateConfigTable() As DataTable
        Try
            ' Create sample Customers table, in order
            ' to demonstrate the behavior of the DataTableReader.
            Dim table As New DataTable
            table.TableName = "MyConfig"

            ' Create two columns, ID and Name.
            Dim idColumn As DataColumn = table.Columns.Add("ID",
                GetType(System.Int32))

            idColumn.AutoIncrement = True
            idColumn.AutoIncrementSeed = 0
            idColumn.AutoIncrementStep = 1
            table.Columns.Add("ConfigName", GetType(System.String))
            table.Columns.Add("Value", GetType(System.String))
            'Set the ID column as the primary key column.
            table.PrimaryKey = New DataColumn() {idColumn}
            Dim newRow As DataRow = table.NewRow()
            newRow("ConfigName") = "MyConnectionString"
            newRow("Value") = ""
            table.Rows.Add(newRow)
            Dim newRow1 As DataRow = table.NewRow()
            newRow1("ConfigName") = "LogErrorsOnly"
            newRow1("Value") = "True"
            table.Rows.Add(newRow1)
            Dim newRow2 As DataRow = table.NewRow()
            newRow2("ConfigName") = "Sett_TaskOverviewKeepInFront"
            newRow2("Value") = "True"
            table.Rows.Add(newRow2)
            Dim newRow3 As DataRow = table.NewRow()
            newRow3("ConfigName") = "Sett_LoadWD_Docs"
            newRow3("Value") = "True"
            table.Rows.Add(newRow3)
            Dim newRow7 As DataRow = table.NewRow()
            newRow7("ConfigName") = "WD_IndexDeleteDocs"
            newRow7("Value") = "False"
            table.Rows.Add(newRow7)
            Dim newRow8 As DataRow = table.NewRow()
            newRow8("ConfigName") = "WD_ShowDocs"
            newRow8("Value") = "False"
            table.Rows.Add(newRow8)
            Dim newRow9 As DataRow = table.NewRow()
            newRow9("ConfigName") = "Sett_ConstructorStart"
            newRow9("Value") = "0"
            table.Rows.Add(newRow9)
            Dim newRow10 As DataRow = table.NewRow()
            newRow10("ConfigName") = "FWSCAN_started"
            newRow10("Value") = "False"
            table.Rows.Add(newRow10)
            Dim newRow11 As DataRow = table.NewRow()
            newRow11("ConfigName") = "Task_Popup_minutes"
            newRow11("Value") = "2"
            table.Rows.Add(newRow11)
            Dim newRow12 As DataRow = table.NewRow()
            newRow12("ConfigName") = "WAN_ENVIRONMENT"
            newRow12("Value") = "False"
            table.Rows.Add(newRow12)
            Dim newRow13 As DataRow = table.NewRow()
            newRow13("ConfigName") = "PATH_ADDON"
            newRow13("Value") = ""
            Dim newRow14 As DataRow = table.NewRow()
            newRow14("ConfigName") = "MyProxyConnectionString"
            newRow14("Value") = ""
            table.Rows.Add(newRow14)
            Dim newRow15 As DataRow = table.NewRow()
            newRow15("ConfigName") = "MyLinkedServer"
            newRow15("Value") = ""
            table.Rows.Add(newRow15)
            Dim newRow16 As DataRow = table.NewRow()
            newRow16("ConfigName") = "MyFormsDesign"
            newRow16("Value") = ""
            Dim newRow17 As DataRow = table.NewRow()
            newRow17("ConfigName") = "GridDocResult_BestFitColumns"
            newRow17("Value") = "True"


            table.AcceptChanges()
            LOGGER.Info("CreateConfigTable su...")
            Return table
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Error in CreateConfigTable" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return Nothing
        End Try
    End Function
    Public Function SaveMySettingsValue(name As String, value As String, type As String)
        Try
            Dim DT As DataTable
            If type = "ConfigMain" Then
                DT = GetTablefromXML(ConfigPath)
            End If
            If type = "ExcludeFilter" Then
                DT = GetTablefromXML(PATH_FileExclusions)
            End If

            If Not DT Is Nothing Then
                For Each Row As DataRow In DT.Rows
                    If Row.Item("ConfigName") = name Then
                        Row.Item("Value") = value
                    End If
                Next
                DT.AcceptChanges()
                DT.WriteXml(ConfigPath)
            Else
                MsgBox("Setting could not be saved! Check logfile.", MsgBoxStyle.Critical)
            End If

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

    End Function
    Public Function Settings_LoadBasicConfig()
        Try
            Dim sql As String = "select * from tbdd_Modules where UPPER(NAME) = UPPER('Record-Organizer')"
            Dim DT As DataTable = MYDB_ECM.GetDatatable(sql)
            If DT.Rows.Count = 1 Then
                vWLaufwerk = DT.Rows(0).Item("STRING1")
                vVERSION_DELIMITER = DT.Rows(0).Item("VERSION_DELIMITER")
                vFILE_DELIMITER = DT.Rows(0).Item("FILE_DELIMITER")
                AUTO_LOGOUT_USER = DT.Rows(0).Item("AUTO_LOGOUT_USER")
                Try
                    DBVERSION = DT.Rows(0).Item("DB_VERSION")
                Catch ex As Exception
                    DBVERSION = "No DB Version-Config"
                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 Module
