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

Public Class ClassInit
    Public _lizenzManager As clsLicenseManager
    Public _database As MSSQLServer

    Public Sub InitLogger()
        LogConfig = New LogConfig(LogConfig.PathType.AppData, Nothing, Nothing, Application.CompanyName, Application.ProductName)
        Logger = LogConfig.GetLogger()
    End Sub
    Public Function InitDatabase()
        Dim dbResult As Boolean
        clsDatabase.GUI = True
        If MyConnectionString <> String.Empty Then
            dbResult = clsDatabase.Init(MyConnectionString)
        Else
            MsgBox("No Databaseconnection configured. (First Start or Appdata not accessible)" & vbNewLine & "Basic-Config will be loaded.", MsgBoxStyle.Information)
            ERROR_INIT = "NO DB-CONNECTION"
            frmConfig_Basic.ShowDialog()
            dbResult = clsDatabase.Init(MyConnectionString)
            InitBasics()
        End If
        If dbResult = False Then
            ERROR_INIT = "FAILED DBCONNECTION"
            MsgBox("Error in init database. (Connection failed) More information in the logfile.", MsgBoxStyle.Critical)
            Return False
        Else
            Return True
        End If
    End Function

    Public Function InitDatabase_New() As Boolean
        If MyConnectionString = String.Empty Then
            MsgBox("No Databaseconnection configured. (First Start or Appdata not accessible)" & vbNewLine & "Basic-Config will be loaded.", MsgBoxStyle.Information)
            ERROR_INIT = "NO DB-CONNECTION"
            frmConfig_Basic.ShowDialog()
        End If

        Try
            Database = New MSSQLServer(LogConfig, MyConnectionString)
            If Database.DBInitialized = True Then
                Return True
            Else
                Return False
            End If

        Catch ex As Exception
            Logger.Error(ex)
            Return False
        End Try
    End Function

    Public Function InitBasics()
        ConfigManager = New ConfigManager(Of ClassConfig)(LogConfig, Application.UserAppDataPath, Application.CommonAppDataPath)

        With ConfigManager.Config
            MyConnectionString = DecryptConnectionString(.ConnectionString)
            LogErrorsOnly = .LogErrorsOnly
            HotkeyFunctionKey = .HotkeyFunctionKey
            HotkeySearchKey = .HotkeySearchKey

            LogConfig.Debug = Not .LogErrorsOnly
        End With

        Return True
    End Function

    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 clsEncryption("!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 CheckModuleData()
        Try
            Dim sql = String.Format("SELECT * FROM [dbo].[FNDD_CHECK_USER_MODULE] ('{0}','CW',{1})", USER_USERNAME, CLIENT_SELECTED)
            Dim DT_CHECKUSER_MODULE As DataTable = Database.GetDatatable(sql)
            If DT_CHECKUSER_MODULE.Rows.Count = 0 Then
                Logger.Info("DT_CHECKUSER_MODULE.Rows.Count = 0", True)
                'ERROR_STATE = "NO USER"
                MsgBox("Sorry - Something went wrong in getting Your rights." & vbNewLine & "Please contact the system administrator!", MsgBoxStyle.Exclamation)
                Return False
            End If
            If DT_CHECKUSER_MODULE.Rows.Count = 1 Then
                Logger.Info(">> Login Username: " & USER_USERNAME, False)
                Logger.Info(">> Login time: " & Now.ToString, False)
                USER_ID = DT_CHECKUSER_MODULE.Rows(0).Item("USER_ID")
                USER_SURNAME = IIf(IsDBNull(DT_CHECKUSER_MODULE.Rows(0).Item("USER_SURNAME")), "", DT_CHECKUSER_MODULE.Rows(0).Item("USER_SURNAME"))
                USER_PRENAME = IIf(IsDBNull(DT_CHECKUSER_MODULE.Rows(0).Item("USER_PRENAME")), "", DT_CHECKUSER_MODULE.Rows(0).Item("USER_PRENAME"))
                USER_SHORTNAME = IIf(IsDBNull(DT_CHECKUSER_MODULE.Rows(0).Item("USER_SHORTNAME")), "", DT_CHECKUSER_MODULE.Rows(0).Item("USER_SHORTNAME"))
                USER_EMAIL = IIf(IsDBNull(DT_CHECKUSER_MODULE.Rows(0).Item("USER_EMAIL")), "", DT_CHECKUSER_MODULE.Rows(0).Item("USER_EMAIL"))
                USER_LANGUAGE = DT_CHECKUSER_MODULE.Rows(0).Item("USER_LANGUAGE")
                USER_DATE_FORMAT = DT_CHECKUSER_MODULE.Rows(0).Item("USER_DATE_FORMAT")

                USER_IN_MODULE = DT_CHECKUSER_MODULE.Rows(0).Item("MODULE_ACCESS")
                USER_IS_ADMIN = DT_CHECKUSER_MODULE.Rows(0).Item("IS_ADMIN")


                USERCOUNT_LOGGED_IN = DT_CHECKUSER_MODULE.Rows(0).Item("USERCOUNT_LOGGED_IN")
                USERCOUNT_LOGGED_IN += 1
                Return True
            Else
                Logger.Info(" - User '" & USER_USERNAME & "' not listed in Useradministration!", 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)
                Return False
            End If
        Catch ex As Exception
            Logger.Error(ex)
            Return False
        End Try

    End Function
    Public Shared Function InitUserLogin(Optional _User As String = "")
        Try
            If _User = "" Then
                USER_USERNAME = Environment.UserName
            Else
                USER_USERNAME = _User
            End If
            Try
                DT_CLIENT_USER = Database.GetDatatable(String.Format("SELECT * FROM VWDD_USER_CLIENT WHERE UPPER(USERNAME) = UPPER('{0}')", Environment.UserName))
                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")
                Else
                    Logger.Info("User '" & USER_USERNAME & "' not related to a client", True)
                    ERROR_INIT = "NO CLIENT"
                    'ERROR_STATE = "NO CLIENT"
                    Return False
                End If
            Catch ex As Exception
                Logger.Info("Unexpected error in checking CLIENT: " & ex.Message)
                CLIENT_SELECTED = 1
            End Try

            If CheckModuleData() = False Then
                Return False
            End If


            If USER_IN_MODULE = False Then
                If USER_IS_ADMIN = False Then
                    Logger.Info(" - User: " & USER_USERNAME & " not related to module!", False)
                    Dim msg = String.Format("Sie sind nicht für die Nutzung dieses Moduls freigeschaltet." & vbNewLine & "Bitte setzen Sie sich mit dem Systemadministrator 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, "Attention:")
                    Return False
                End If
            End If
            'Am System anmelden
            ClassLicense.Refresh_Licence(DT_CLIENT_USER.Rows(0).Item("CLIENT_ID"))
            'Am System anmelden
            ' sql = String.Format("UPDATE TBDD_USER SET LOGGED_IN = 1, LOGGED_WHERE = '{0}' WHERE GUID = {1}", Environment.MachineName, USER_ID)
            'Database.GetDatatable(sql)
            Dim oSQL As String
            oSQL = "DELETE FROM TBDD_USER_MODULE_LOG_IN WHERE USER_ID = " & USER_ID & " AND MODULE = 'Clipboard-Watcher'"
            Database.ExecuteNonQuery(oSQL)

            oSQL = String.Format("INSERT INTO TBDD_USER_MODULE_LOG_IN (USER_ID,CLIENT_ID,MODULE,VERSION_CLIENT,MACHINE_NAME) VALUES ({0},{1},'Clipboard-Watcher','{2}','{3}')", USER_ID, 0, My.Application.Info.Version.ToString, Environment.MachineName)
            Database.ExecuteNonQuery(oSQL)

            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
                '    'Admin
                '    pageAdmin.Visible = True
            End If

            WD_UNICODE = Database.GetScalarValue("SELECT WD_UNICODE FROM TBCW_CONFIGURATION WHERE GUID = 1")
            GDPICTURE_LICENSE = Database.GetScalarValue("SELECT LICENSE FROM TBDD_3RD_PARTY_MODULES WHERE NAME = 'GDPICTURE'")

            Logger.Debug(" >> Count Users logged in: " & USERCOUNT_LOGGED_IN.ToString, False)
            If LICENSE_COUNT < USERCOUNT_LOGGED_IN And LICENSE_EXPIRED = False Then
                Dim msg = String.Format("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!")

                If USER_LANGUAGE <> "de-DE" Then
                    msg = String.Format("The number of logged Users (" & USERCOUNT_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.Info(" >> The number of logged Users (" & USERCOUNT_LOGGED_IN.ToString & ") exceeds the number of licenses (" & LICENSE_COUNT & ") ", False)
                If USER_IS_ADMIN = False Then
                    'Anmeldung wieder herausnehmen
                    oSQL = "DELETE FROM TBDD_USER_MODULE_LOG_IN WHERE USER_ID = " & USER_ID & " AND MODULE= 'Clipboard-Watcher'"
                    Database.ExecuteNonQuery(oSQL)
                    Logger.Info(" - logged out the user", False)
                    Return False
                End If
            End If
            Return True


        Catch ex As Exception
            Logger.Info("Unexpected Error in InitUserLogin: " & ex.Message, True)
            MsgBox("Unexpected Error in InitUserLogin: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try

    End Function

    Public Shared Sub Refresh_Connections()
        Try
            Dim oSql = String.Format("SELECT * FROM TBDD_CONNECTION")
            Dim oDatatable As New MyDataset.TBDD_CONNECTIONDataTable()
            Dim oResult = Database.GetDatatable(oSql)

            oDatatable.Merge(oResult)

            DT_CONNECTIONS = oDatatable
        Catch ex As Exception
            Logger.Error(ex)
            MsgBox("Unexpected Error in Refresh_Connections: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Public Shared Function Refresh_Profile_Links() As String
        Dim oWhereClause = $"T1.USER_ID = {USER_ID} OR GROUP_ID IN (SELECT DISTINCT GUID FROM TBDD_GROUPS WHERE GUID IN (SELECT GROUP_ID FROM TBDD_GROUPS_USER WHERE USER_ID = {USER_ID}))"

        Dim ProfileSQL As String = $"SELECT DISTINCT GUID, NAME,REGEX_EXPRESSION,COMMENT,PROC_NAME,PROFILE_TYPE FROM VWCW_USER_PROFILE T1 WHERE {oWhereClause}"
        Dim oProcessSQL As String = $"SELECT DISTINCT T.GUID, T.PROFILE_ID,T.PROC_NAME FROM TBCW_PROFILE_PROCESS T, VWCW_USER_PROFILE T1 WHERE T.PROFILE_ID = T1.GUID AND ({oWhereClause})"
        Dim oWindowSQL As String = $"SELECT DISTINCT T.* FROM VWCW_PROFILE_REL_WINDOW T, VWCW_USER_PROFILE T1 WHERE T.PROFILE_ID = T1.GUID AND ({oWhereClause})"
        Dim oControlSQL As String = $"SELECT DISTINCT T.* FROM VWCW_PROFILE_REL_CONTROL T, VWCW_USER_PROFILE T1 WHERE T.PROFILE_ID = T1.GUID AND ({oWhereClause})"

        Try
            DT_USER_PROFILES = Database.GetDatatable(ProfileSQL)

            If DT_USER_PROFILES Is Nothing OrElse DT_USER_PROFILES.Rows.Count = 0 Then
                Return "Es wurden noch keine Profile für den aktuellen Benutzer konfiguriert."
            End If

            DTPROFILE_REL_PROCESS = Database.GetDatatable(oProcessSQL)
            DTPROFILE_REL_WINDOW = Database.GetDatatable(oWindowSQL)
            DTPROFILE_REL_CONTROL = Database.GetDatatable(oControlSQL)
        Catch ex As Exception
            Logger.Error(ex)
            MsgBox("Unexpected Error in Refresh_Profile_Links: " & ex.Message, MsgBoxStyle.Critical)
            Return "Fehler bei Aktualisierung!"
        End Try

        Return "Aktualisierung erfolgreich."
    End Function
End Class
