Imports DD_LIB_Standards
Imports DevExpress.XtraEditors
Imports DevExpress.XtraEditors.Controls
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Grid
Imports DigitalData.Controls.RegexEditor
Imports DigitalData.Modules.Windows.Window

Public Class ctrlApplicationAssignment
    Public Property SelectedProfileId As Integer = 0
    Public Property SelectedProcessId As Integer = 0
    Public Property SelectedWindowId As Integer = 0
    Public Property SelectedControlId As Integer = 0

    Public Sub New()
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        TBCW_PROFILE_PROCESSTableAdapter.Connection.ConnectionString = MyConnectionString
        TBCW_PROF_REL_WINDOWTableAdapter.Connection.ConnectionString = MyConnectionString
        TBCW_PROF_REL_CONTROLTableAdapter.Connection.ConnectionString = MyConnectionString
    End Sub

    Private Sub ctrlApplicationAssignment_Load(sender As Object, e As EventArgs) Handles Me.Load
        AddHandler RepositoryItemRegexEdit.ButtonClick, AddressOf RepositoryItemRegexEdit_Click
        AddHandler RepositoryItemButtonEdit1.ButtonClick, AddressOf RepositoryItemRegexEdit_Click
    End Sub

    Public Function AssignProfileID(ProfileId As Integer) As Boolean
        Try
            SelectedProfileId = ProfileId
            Return True
        Catch ex As Exception
            Logger.Error(ex)
            Return False
        End Try
    End Function
    Public Function Process_Load(ProfileId As Integer) As Boolean
        Try
            TBCW_PROFILE_PROCESSTableAdapter.Fill(MyDataset.TBCW_PROFILE_PROCESS, ProfileId)
            Return True
        Catch ex As Exception
            Logger.Error(ex)
            Return False
        End Try
    End Function

    Public Function Process_CreateAssignment(ProfileId As Integer) As Boolean
        Dim oForm As New frmProcessCapture()
        Dim oResult = oForm.ShowDialog()

        If oResult = DialogResult.OK Then
            Try
                Dim oWindowTitle As String = GetSQLFriendlyString(oForm.WindowTitle)
                Dim oProcessName As String = oForm.ProcessName

                If oProcessName <> "" Then
                    Dim oSQL = String.Format("INSERT INTO TBCW_PROFILE_PROCESS (PROFILE_ID,PROC_NAME,ADDED_WHO) VALUES ({0},'{1}','{2}')", ProfileId, oProcessName, Environment.UserName)
                    If Database.ExecuteNonQuery(oSQL) = False Then
                        Return False
                    Else
                        Dim oNewProcessId = Database.GetScalarValue("SELECT MAX(GUID) FROM TBCW_PROFILE_PROCESS")

                        oSQL = String.Format("INSERT INTO TBCW_PROF_REL_WINDOW (DESCRIPTION, REGEX, ADDED_WHO, PROCESS_ID) VALUES ('{0}', '^{1}$', '{2}' ,{3})", oWindowTitle, oWindowTitle, Environment.UserName, oNewProcessId)
                        If Database.ExecuteNonQuery(oSQL) = False Then
                            Return False
                        End If
                    End If
                End If

                Process_Load(SelectedProfileId)
                Return True
            Catch ex As Exception
                Logger.Error(ex)
                Return False
            End Try
        Else
            Return True
        End If
    End Function

    Public Function Process_DeleteAssignment() As Boolean
        Try
            Dim oProcessId = GridViewProcessProfile.GetFocusedRowCellValue(GridViewProcessProfile.Columns("GUID"))
            Dim oSQL = String.Format("EXEC PRCW_DELETE_PROCESS {0}", oProcessId)
            If Database.ExecuteNonQuery(oSQL) Then
                Process_Load(SelectedProfileId)
                Return True
            End If

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

    Public Function Window_Load() As Boolean
        Try
            TBCW_PROF_REL_WINDOWTableAdapter.Fill(MyDataset.TBCW_PROF_REL_WINDOW, CURRENT_PROCESSID)

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

    Private Sub RepositoryItemRegexEdit_Click(sender As Object, e As ButtonPressedEventArgs)
        Dim oButtonEdit As ButtonEdit = sender
        Dim oGridControl As GridControl = oButtonEdit.Parent
        Dim oGridView As GridView = oGridControl.FocusedView
        Dim oRowHandle As Integer = oGridView.FocusedRowHandle

        Dim oForm As New frmRegexEditor(oButtonEdit.EditValue)
        If oForm.ShowDialog() = DialogResult.OK Then
            oButtonEdit.EditValue = oForm.RegexString
        End If
        Console.WriteLine()
    End Sub

    Public Function Window_CreateAssignment(ProfileId As Integer) As Boolean
        Dim oRow = GridViewProcessProfile.GetDataRow(GridViewProcessProfile.FocusedRowHandle)
        Dim oCurrentProcess = oRow.Item("PROC_NAME")

        Dim oForm As New frmProcessCapture(oCurrentProcess)
        Dim oResult = oForm.ShowDialog()

        If oResult = DialogResult.OK Then
            Try
                Dim oWindowTitle As String = GetSQLFriendlyString(oForm.WindowTitle)
                Dim oProcessName As String = oForm.ProcessName

                If oWindowTitle <> "" Then
                    Dim insert = String.Format("INSERT INTO TBCW_PROF_REL_WINDOW (DESCRIPTION, REGEX, ADDED_WHO,PROCESS_ID) VALUES ('{0}', '^{1}$','{2}',{3})", oWindowTitle, oWindowTitle, Environment.UserName, CURRENT_PROCESSID)
                    If Database.ExecuteNonQuery(insert) = False Then
                        Return False
                    End If
                End If

                Window_Load()
                Return True
            Catch ex As Exception
                Logger.Error(ex)
                Return False
            End Try
        Else
            Return True
        End If
    End Function

    Public Function Window_DeleteAssignment() As Boolean
        Try
            Dim oGuid = GridView_Window.GetFocusedRowCellValue(GridView_Window.Columns("GUID"))
            Dim oSQL = String.Format("EXEC PRCW_DELETE_WINDOW {0}", oGuid)
            If Database.ExecuteNonQuery(oSQL) Then
                Process_Load(SelectedProfileId)
                Return True
            End If

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

    Public Function Window_SaveAssignment() As Boolean
        Try
            TBCW_PROF_REL_WINDOWBindingSource.EndEdit()
            GridView_Window.CloseEditor()
            If Not IsNothing(MyDataset.TBCW_PROF_REL_WINDOW.GetChanges) Then
                TBCW_PROF_REL_WINDOWBindingSource.EndEdit()
                TBCW_PROF_REL_WINDOWTableAdapter.Update(MyDataset.TBCW_PROF_REL_WINDOW)
                Return True
            End If

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

    Public Function Control_Load() As Boolean
        Try
            TBCW_PROF_REL_CONTROLTableAdapter.Fill(MyDataset.TBCW_PROF_REL_CONTROL, SelectedWindowId)

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

    Public Function Control_CreateAssignment() As Boolean
        Dim oForm As New frmControlCapture(EditMode:=False)
        Dim oResult = oForm.ShowDialog()

        If oResult = DialogResult.OK Then
            Try
                Dim oSql = $"INSERT INTO TBCW_PROF_REL_CONTROL 
                            (
                                WINDOW_ID, DESCRIPTION, CONTROL_NAME, ADDED_WHO
                                ,[TOPLEFT_TOP],[TOPLEFT_LEFT],[TOPLEFT_RIGHT],[TOPLEFT_BOTTOM]
                                ,[TOPRIGHT_TOP],[TOPRIGHT_LEFT],[TOPRIGHT_RIGHT],[TOPRIGHT_BOTTOM]
                                ,[BOTTOMLEFT_TOP],[BOTTOMLEFT_LEFT],[BOTTOMLEFT_RIGHT],[BOTTOMLEFT_BOTTOM]
                                ,[BOTTOMRIGHT_TOP],[BOTTOMRIGHT_LEFT],[BOTTOMRIGHT_RIGHT],[BOTTOMRIGHT_BOTTOM]
                            ) VALUES (
                                {SelectedWindowId}, 'Beispiel Beschreibung', '{oForm.ControlName}', '{Environment.UserName}',
                                {oForm.TopLeft.Top}, {oForm.TopLeft.Left}, {oForm.TopLeft.Right}, {oForm.TopLeft.Bottom},
                                {oForm.TopRight.Top}, {oForm.TopRight.Left}, {oForm.TopRight.Right}, {oForm.TopRight.Bottom},
                                {oForm.TopLeft.Top}, {oForm.TopLeft.Left}, {oForm.TopLeft.Right}, {oForm.TopLeft.Bottom},
                                {oForm.TopLeft.Top}, {oForm.TopLeft.Left}, {oForm.TopLeft.Right}, {oForm.TopLeft.Bottom}
                            )"

                If Database.ExecuteNonQuery(oSql) = False Then
                    Return False
                End If


                Control_Load()
                Return True
            Catch ex As Exception
                Logger.Error(ex)
                Return False
            End Try
        Else
            Return True
        End If
    End Function

    Public Function Control_EditAssignment() As Boolean
        Dim oHandles As List(Of Integer) = GridView_Control.
            GetSelectedRows().
            ToList()

        If oHandles.Count <> 1 Then
            Return False
        End If

        Dim oHandle As Integer = oHandles.FirstOrDefault()
        Dim oRow = GridView_Control.GetDataRow(oHandle)

        Dim oControlName As String = oRow.Item("CONTROL_NAME")
        Dim oTopLeft As New RectangleInfo() With {
            .Top = oRow.Item("TOPLEFT_TOP"),
            .Left = oRow.Item("TOPLEFT_LEFT"),
            .Right = oRow.Item("TOPLEFT_RIGHT"),
            .Bottom = oRow.Item("TOPLEFT_BOTTOM")
        }

        Dim oTopRight As New RectangleInfo() With {
            .Top = oRow.Item("TOPRIGHT_TOP"),
            .Left = oRow.Item("TOPRIGHT_LEFT"),
            .Right = oRow.Item("TOPRIGHT_RIGHT"),
            .Bottom = oRow.Item("TOPRIGHT_BOTTOM")
        }

        Dim oBottomLeft As New RectangleInfo() With {
            .Top = oRow.Item("BOTTOMLEFT_TOP"),
            .Left = oRow.Item("BOTTOMLEFT_LEFT"),
            .Right = oRow.Item("BOTTOMLEFT_RIGHT"),
            .Bottom = oRow.Item("BOTTOMLEFT_BOTTOM")
        }

        Dim oBottomRight As New RectangleInfo() With {
            .Top = oRow.Item("BOTTOMRIGHT_TOP"),
            .Left = oRow.Item("BOTTOMRIGHT_LEFT"),
            .Right = oRow.Item("BOTTOMRIGHT_RIGHT"),
            .Bottom = oRow.Item("BOTTOMRIGHT_BOTTOM")
        }

        Dim oBounds As String = frmControlCapture.GetBoundsString(oTopLeft, oTopRight, oBottomLeft, oBottomRight)
        Dim oForm As New frmControlCapture(EditMode:=True, ControlBounds:=oBounds, ControlName:=oControlName)
        oForm.TopLeft = oTopLeft
        oForm.TopRight = oTopRight
        oForm.BottomLeft = oBottomLeft
        oForm.BottomRight = oBottomRight

        Dim oResult = oForm.ShowDialog()

        If oResult = DialogResult.OK Then
            Try
                Dim oSql = $"UPDATE TBCW_PROF_REL_CONTROL SET                             
                            CONTROL_NAME = '{oForm.ControlName}',
                            CHANGED_WHO = '{Environment.UserName}',
                            [TOPLEFT_TOP] = {oForm.TopLeft.Top},
                            [TOPLEFT_BOTTOM] = {oForm.TopLeft.Bottom},
                            [TOPLEFT_LEFT] = {oForm.TopLeft.Left},
                            [TOPLEFT_RIGHT] = {oForm.TopLeft.Right},
                            [TOPRIGHT_TOP] = {oForm.TopRight.Top},
                            [TOPRIGHT_BOTTOM] = {oForm.TopRight.Bottom},
                            [TOPRIGHT_LEFT] = {oForm.TopRight.Left},
                            [TOPRIGHT_RIGHT] = {oForm.TopRight.Right},
                            [BOTTOMLEFT_TOP] = {oForm.BottomLeft.Top},
                            [BOTTOMLEFT_BOTTOM] = {oForm.BottomLeft.Bottom},
                            [BOTTOMLEFT_LEFT] = {oForm.BottomLeft.Left},
                            [BOTTOMLEFT_RIGHT] = {oForm.BottomLeft.Right},
                            [BOTTOMRIGHT_TOP] = {oForm.BottomRight.Top},
                            [BOTTOMRIGHT_BOTTOM] = {oForm.BottomRight.Bottom},
                            [BOTTOMRIGHT_LEFT] = {oForm.BottomRight.Left},
                            [BOTTOMRIGHT_RIGHT] = {oForm.BottomRight.Right}
                            WHERE GUID = {SelectedControlId}
                            "

                If Database.ExecuteNonQuery(oSql) = False Then
                    Return False
                End If


                Control_Load()
                Return True
            Catch ex As Exception
                Logger.Error(ex)
                Return False
            End Try
        Else
            Return True
        End If
    End Function

    Public Function Control_SaveAssignment() As Boolean
        Try
            TBCW_PROF_REL_CONTROLBindingSource.EndEdit()
            GridView_Control.CloseEditor()
            If Not IsNothing(MyDataset.TBCW_PROF_REL_CONTROL.GetChanges) Then
                TBCW_PROF_REL_CONTROLBindingSource.EndEdit()
                TBCW_PROF_REL_CONTROLTableAdapter.Update(MyDataset.TBCW_PROF_REL_CONTROL)
            End If

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

    Public Function Control_DeleteAssignment() As Boolean
        Try
            Dim oGuid = GridView_Control.GetFocusedRowCellValue(GridView_Control.Columns("GUID"))
            Dim oSQL = String.Format("DELETE FROM TBCW_PROF_REL_CONTROL WHERE GUID = {0}", oGuid)
            If Database.ExecuteNonQuery(oSQL) Then
                Window_Load()
                Return True
            End If

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

    Private Sub GridViewProcessProfile_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridViewProcessProfile.FocusedRowChanged
        MyDataset.TBCW_PROF_REL_CONTROL.Clear()
        MyDataset.TBCW_PROF_REL_WINDOW.Clear()

        If e.FocusedRowHandle < 0 Then
            SelectedProcessId = 0
            Exit Sub
        End If

        Dim oSelectedRow As DataRow = GridViewProcessProfile.GetDataRow(e.FocusedRowHandle)
        Dim oProcessName As String = oSelectedRow.Item("PROC_NAME")
        Dim oProcessGUID = oSelectedRow.Item("GUID")
        CURRENT_PROCESSID = oProcessGUID
        CURRENT_PROCESSNAME = oProcessName

        SelectedProcessId = oProcessGUID

        If Window_Load() = False Then
            MsgBox($"Error while loading windows for process {oProcessName}", vbCritical, "")
        End If
    End Sub

    Private Function GetSQLFriendlyString(UnfriendlyString As String) As String
        Return UnfriendlyString.
            Trim().
            Replace(vbNullChar, "")
    End Function

    Private Sub GridView_Window_FocusedRowChanged(sender As Object, e As Views.Base.FocusedRowChangedEventArgs) Handles GridView_Window.FocusedRowChanged
        Try
            If e.FocusedRowHandle < 0 Then
                SelectedWindowId = 0
                Exit Sub
            End If

            Dim oSelectedRow As DataRow = GridView_Window.GetDataRow(e.FocusedRowHandle)
            Dim oWindowId As String = oSelectedRow.Item("GUID")

            SelectedWindowId = oWindowId

            If Control_Load() = False Then
                MsgBox($"Error while loading controls for window {oWindowId}", vbCritical, "")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub GridView_Control_FocusedRowChanged(sender As Object, e As Views.Base.FocusedRowChangedEventArgs) Handles GridView_Control.FocusedRowChanged
        If e.FocusedRowHandle < 0 Then
            SelectedControlId = 0
            Exit Sub
        End If

        Dim oSelectedRow As DataRow = GridView_Control.GetDataRow(e.FocusedRowHandle)
        Dim oControlGUID = oSelectedRow.Item("GUID")

        SelectedControlId = oControlGUID
    End Sub
End Class
