Imports DigitalData.Modules.EDMI.API
Imports DigitalData.Modules.Logging

Namespace ClipboardWatcher
    Public Class ClassProfileLoader
        Private ReadOnly LogConfig As LogConfig
        Private ReadOnly Logger As Logger
        Private ReadOnly Database As DatabaseWithFallback

        Public Sub New(LogConfig As LogConfig, Database As DatabaseWithFallback)
            Me.LogConfig = LogConfig
            Me.Logger = LogConfig.GetLogger()
            Me.Database = Database
        End Sub

        Public Function LoadProfiles() As Boolean
            Try
                Dim oUserId = My.Application.User.UserId
                Dim oWhereClause = $"T1.USER_ID = {oUserId} OR GROUP_ID IN (SELECT DISTINCT GUID FROM TBDD_GROUPS WHERE GUID IN (SELECT GROUP_ID FROM TBDD_GROUPS_USER WHERE USER_ID = {oUserId}))"

                Dim oProfileSQL 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})"

                Dim oUserProfiles = Database.GetDatatable("VWCW_USER_PROFILE", oProfileSQL, Constants.DatabaseType.ECM)
                Dim oProfileProcesses = Database.GetDatatable("VWCW_PROFILE_REL_WINDOW", oProcessSQL, Constants.DatabaseType.ECM)
                Dim oProfileWindows = Database.GetDatatable("VWCW_PROFILE_REL_WINDOW", oWindowSQL, Constants.DatabaseType.ECM)
                Dim oProfileControls = Database.GetDatatable("VWCW_PROFILE_REL_CONTROL", oControlSQL, Constants.DatabaseType.ECM)

                My.Application.ClipboardWatcher.UserProfiles = oUserProfiles
                My.Application.ClipboardWatcher.ProfileProcesses = oProfileProcesses
                My.Application.ClipboardWatcher.ProfileWindows = oProfileWindows
                My.Application.ClipboardWatcher.ProfileControls = oProfileControls
                My.Application.ClipboardWatcher.MonitoringActive = True

                Return True

            Catch ex As Exception
                Logger.Error(ex)

                Return False

            End Try
        End Function
    End Class

End Namespace

