Imports System.ComponentModel
Imports System.IO
Imports DevExpress.Utils
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.XtraPrinting
Imports DigitalData.GUIs.Common

Public Class frmMonitor
    Dim DT_MONITOR_KONFIG As DataTable
    Dim GRID1_TITLE As String
    Dim GRID2_TITLE As String
    Dim GRID2_SQL As String
    Dim GRID3_TITLE As String
    Dim GRID3_SQL As String
    Dim GRID4_TITLE As String
    Dim GRID4_SQL As String

    Private _GridBuilder As GridBuilder
    Private _ActiveGrid As GridControl = Nothing
    ' Public Property für die Monitor-ID
    Public Property MonitorID As Integer
    ' Private _frmDocView As frmDocView 'You need a reference to Form1
    Dim FormShown As Boolean = False

    ' Konstruktor mit optionalem Parameter
    Public Sub New(Optional pMonitorID As Integer = 0)
        InitializeComponent()
        MonitorID = pMonitorID
    End Sub
    Private Sub GridView1_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridView1.FocusedRowChanged
        If FormShown = False Then Exit Sub
        Load_Detail()

    End Sub
    Sub Load_Detail()
        If FormShown = False Then Exit Sub
        Dim oDocPath As String = String.Empty
        Try
            Dim oDocID
            Try
                oDocID = GridView1.GetFocusedRowCellValue(GridView1.Columns("DocID"))
            Catch ex As Exception
                Try
                    oDocID = GridView1.GetFocusedRowCellValue(GridView1.Columns("ObjectID"))
                Catch ex1 As Exception
                    LOGGER.Warn("⚠️ Could not get Doc/ObjectReference: " & ex.Message)
                    MsgBox("Could not get Doc/ObjectReference: " & ex.Message, MsgBoxStyle.Critical, "Load_Detail")
                    Exit Sub
                End Try
            End Try

            If IsNothing(oDocID) Then
                Exit Sub
            End If

            Try
                oDocPath = GridView1.GetFocusedRowCellValue(GridView1.Columns("FULL_FILE_PATH"))
            Catch ex As Exception
                LOGGER.Warn($"Error getting DocPath in Monitor: {ex.Message}")
                oDocPath = String.Empty
            End Try
            BarStaticItemInfoDoc.Caption = $"DocID: {oDocID} - Docpath: {oDocPath}"
            If Not IsNothing(GRID2_SQL) Then
                Dim oDetailSQL = GRID2_SQL
                oDetailSQL = oDetailSQL.Replace("@DocID", oDocID)
                oDetailSQL = oDetailSQL.Replace("@IDBOBJID", oDocID)
                oDetailSQL = oDetailSQL.Replace("@UserID", USER_ID)
                oDetailSQL = oDetailSQL.Replace("@UserName", USER_USERNAME)
                Dim oDT2 As DataTable = DatabaseFallback.GetDatatableECM(oDetailSQL) ', "Monitor_Detail1")
                If Not IsNothing(oDT2) Then
                    LOGGER.Debug($"Found {oDT2.Rows.Count} rows for GridView2")
                    GridView2.Columns.Clear()
                    GridControl2.DataSource = oDT2
                    Format_Datetime_Columns(GridView2, "Grid 2")

                End If
                If DT_MONITOR_KONFIG.Rows.Count > 2 Then
                    LOGGER.Debug($"DT_MONITOR_KONFIG.Rows.Count > 2")
                    oDetailSQL = GRID3_SQL
                    oDetailSQL = oDetailSQL.Replace("@DocID", oDocID)
                    oDetailSQL = oDetailSQL.Replace("@IDBOBJID", oDocID)
                    oDetailSQL = oDetailSQL.Replace("@UserID", USER_ID)
                    oDetailSQL = oDetailSQL.Replace("@UserName", USER_USERNAME)
                    Dim oDT3 As DataTable = DatabaseFallback.GetDatatableECM(oDetailSQL) ', "Monitor_Detail2")
                    LOGGER.Debug($"oDetailSQL for Grid 3: {oDetailSQL}")
                    If Not IsNothing(oDT3) Then
                        LOGGER.Debug($"Found {oDT3.Rows.Count} rows for GridView3")
                        GridView3.Columns.Clear()
                        GridControl3.DataSource = oDT3
                        Format_Datetime_Columns(GridView3, "Grid 3")
                    End If
                    If DT_MONITOR_KONFIG.Rows.Count = 4 Then
                        LOGGER.Debug($"DT_MONITOR_KONFIG.Rows.Count = 4")
                        oDetailSQL = GRID4_SQL
                        oDetailSQL = oDetailSQL.Replace("@DocID", oDocID)
                        oDetailSQL = oDetailSQL.Replace("@IDBOBJID", oDocID)
                        oDetailSQL = oDetailSQL.Replace("@UserID", USER_ID)
                        oDetailSQL = oDetailSQL.Replace("@UserName", USER_USERNAME)
                        LOGGER.Debug($"oDetailSQL for Grid 4: {oDetailSQL}")
                        Dim oDT4 As DataTable = DatabaseFallback.GetDatatableECM(oDetailSQL) ', "Monitor_Detail3")
                        If Not IsNothing(oDT4) Then
                            LOGGER.Debug($"Found {oDT4.Rows.Count} rows for GridView4")
                            GridView4.Columns.Clear()
                            GridControl4.DataSource = oDT4
                            Format_Datetime_Columns(GridView4, "Grid 4")
                            'Try
                            '    GridView4.Columns("Geändert wann").DisplayFormat.FormatType = FormatType.DateTime
                            '    GridView4.Columns("Geändert wann").DisplayFormat.FormatString = "dd.MM.yyyy HH:MM:ss"
                            'Catch ex As Exception
                            '    GridView4.Columns("Changed when").DisplayFormat.FormatType = FormatType.DateTime
                            '    GridView4.Columns("Changed when").DisplayFormat.FormatString = "dd.MM.yyyy HH:MM:ss"
                            'End Try
                        End If
                    End If
                End If
            End If




        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error GridView1.FocusedRowChanged:")
        Finally
            If oDocPath <> String.Empty Then
                Load_Doc(oDocPath)
            End If

        End Try

    End Sub
    Sub Format_Datetime_Columns(pGridView As GridView, pWhichGridView As String)
        Dim oColExists As Boolean = False
        Try

            If MON_ADDED_COLUMN <> "None" Then
                MON_ADDED_COLUMN = MON_ADDED_COLUMN.Replace("[", "")
                MON_ADDED_COLUMN = MON_ADDED_COLUMN.Replace("]", "")
                For Each ocol As Columns.GridColumn In pGridView.Columns
                    If ocol.ToString = MON_ADDED_COLUMN Then
                        oColExists = True
                        Exit For
                    End If
                Next
                If oColExists Then
                    pGridView.Columns(MON_ADDED_COLUMN).DisplayFormat.FormatType = FormatType.DateTime
                    pGridView.Columns(MON_ADDED_COLUMN).DisplayFormat.FormatString = "dd.MM.yyyy HH:MM:ss"
                End If

            End If

        Catch ex As Exception
            LOGGER.Warn($"Error formatting column [{MON_ADDED_COLUMN}] {ex.Message} - Check wether it exists in columns of GridView [{pWhichGridView}]!")
        End Try
        Try
            If MON_EDITED_COLUMN <> "None" Then
                oColExists = False
                For Each ocol As Columns.GridColumn In pGridView.Columns
                    If ocol.ToString = MON_EDITED_COLUMN Then
                        oColExists = True
                        Exit For
                    End If
                Next
                If oColExists Then
                    pGridView.Columns(MON_EDITED_COLUMN).DisplayFormat.FormatType = FormatType.DateTime
                    pGridView.Columns(MON_EDITED_COLUMN).DisplayFormat.FormatString = "dd.MM.yyyy HH:MM:ss"
                End If

            End If

        Catch ex As Exception
            LOGGER.Warn($"Error formatting column [{MON_EDITED_COLUMN}] {ex.Message} - Check wether it exists in columns of GridView [{pWhichGridView}]!")
        End Try
    End Sub
    Sub Load_Doc(oDocPath As String)
        Try
            If SplitContainerControlMain.Collapsed = False And oDocPath <> String.Empty Then
                'If Not Application.OpenForms().OfType(Of frmValidator).Any Then
                '    frmDocView.Show()
                '    _frmDocView = frmDocView
                'End If
                '_frmDocView.LoadFile(oDocPath)

                If File.Exists(oDocPath) Then
                    DocumentViewerMonitor.LoadFile_FromPath(oDocPath)
                    BarStaticItemInfo.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                    DocumentViewerMonitor.Visible = True
                    ' DocumentViewerMonitor.RightOnlyView(USER_RIGHT_VIEW_ONLY)

                Else
                    BarStaticItemInfo.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                    BarStaticItemInfo.Caption = $"File is not existing or accessible!"
                    DocumentViewerMonitor.Visible = False
                End If


            End If
        Catch ex As Exception
            LOGGER.Error(ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in LoadDoc:")
        End Try
    End Sub
    Private Async Sub frmMonitor_Load(sender As Object, e As EventArgs) Handles Me.Load
        SplitContainerControlMain.Collapsed = True
        Me.Text = COCKPIT_MONITOR_CAPTION
        Dim _GridList As New List(Of GridView) From {
            GridView1,
            GridView2,
            GridView3,
            GridView4
        }
        _GridBuilder = New GridBuilder(_GridList).
            WithReadOnlyOptions().
            WithClipboardHandler()

        GridView1.ShowLoadingPanel()
        Await Load_Grid_Data()
        GridView1.HideLoadingPanel()

        Select Case DT_MONITOR_KONFIG.Rows.Count
            Case 2
                LoadGridLayout(1)
                LoadGridLayout(2)
                SplitContainerControl1.SplitterPosition = CONFIG.Config.MonitorSplitter1_Distance
            Case 3
                LoadGridLayout(1)
                LoadGridLayout(2)
                LoadGridLayout(3)
                SplitContainerControl1.SplitterPosition = CONFIG.Config.MonitorSplitter1_Distance
                SplitContainerControl2.SplitterPosition = CONFIG.Config.MonitorSplitter2_Distance
            Case 4
                LoadGridLayout(1)
                LoadGridLayout(2)
                LoadGridLayout(3)
                LoadGridLayout(4)
                SplitContainerControl1.SplitterPosition = CONFIG.Config.MonitorSplitter1_Distance
                SplitContainerControl2.SplitterPosition = CONFIG.Config.MonitorSplitter2_Distance
                SplitContainerControl3.SplitterPosition = CONFIG.Config.MonitorSplitter3_Distance
        End Select
        Try
            DocumentViewerMonitor.Init(LOGCONFIG, GDPICTURE_LICENSE, New DigitalData.Controls.DocumentViewer.DocumentViewer.ToolbarSettings() With {
            .ShowPrintButton = True,
            .ShowRotateButton = True,
            .ShowFlipButton = True,
            .ShowSettingButton = True
        })
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub
    Async Function Load_Grid_Data() As Threading.Tasks.Task
        Try
            FormShown = False
            Dim oSQL = $"SELECT * FROM TBPM_MONITOR_KONFIG (NOLOCK) WHERE COCKPIT_ID = {COCKPIT_MONITOR_ID}"
            DT_MONITOR_KONFIG = DatabaseFallback.GetDatatableECM(oSQL) ', "Monitor-Load_Grid_Data1")
            If DT_MONITOR_KONFIG Is Nothing OrElse DT_MONITOR_KONFIG.Rows.Count = 0 Then
                MsgBox("No configuration found for this monitor cockpit. Please contact your administrator.", MsgBoxStyle.Critical, "No Configuration")
                Me.Close()
            End If

            oSQL = DT_MONITOR_KONFIG.Rows(0).Item("GRID_SQL")
            GridView1.Columns.Clear()
            Dim oDTGRID1 As DataTable = Await DatabaseFallback.GetDatatableECMAsync(oSQL) ', "Monitor-Load_Grid_Data2")
            GridControl1.DataSource = oDTGRID1

            GRID1_TITLE = DT_MONITOR_KONFIG.Rows(0).Item("GRID_TITLE")
            GridView1.ViewCaption = GRID1_TITLE
            Format_Datetime_Columns(GridView1, "Grid 1")
            Try
                'GridView1.Columns.Item("FULL_FILE_PATH").Visible = False
            Catch ex As Exception
                LOGGER.Info($"Attention: No Column FULL_FILE_PATH in GridView1")
            End Try
            Select Case DT_MONITOR_KONFIG.Rows.Count
                Case 2
                    SplitContainerControl2.Collapsed = True
                Case 3
                    SplitContainerControl3.Collapsed = True
                Case Else
                    SplitContainerControl2.Collapsed = False
                    SplitContainerControl3.Collapsed = False
            End Select
            If DT_MONITOR_KONFIG.Rows.Count > 1 Then
                GRID2_TITLE = DT_MONITOR_KONFIG.Rows(1).Item("GRID_TITLE")
                GRID2_SQL = DT_MONITOR_KONFIG.Rows(1).Item("GRID_SQL")
                GridView2.ViewCaption = GRID2_TITLE
                Select Case DT_MONITOR_KONFIG.Rows.Count
                    Case 3
                        GRID3_TITLE = DT_MONITOR_KONFIG.Rows(2).Item("GRID_TITLE")
                        GRID3_SQL = DT_MONITOR_KONFIG.Rows(2).Item("GRID_SQL")
                        GridView3.ViewCaption = GRID3_TITLE
                    Case 4
                        GRID3_TITLE = DT_MONITOR_KONFIG.Rows(2).Item("GRID_TITLE")
                        GRID3_SQL = DT_MONITOR_KONFIG.Rows(2).Item("GRID_SQL")
                        GridView3.ViewCaption = GRID3_TITLE
                        GRID4_TITLE = DT_MONITOR_KONFIG.Rows(3).Item("GRID_TITLE")
                        GRID4_SQL = DT_MONITOR_KONFIG.Rows(3).Item("GRID_SQL")
                        GridView4.ViewCaption = GRID4_TITLE
                End Select
            End If




        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Load_Grid_Data:")
        Finally
            FormShown = True
        End Try
    End Function
    Private Function GetGridLayoutPath(pGridNumber As Integer) As String
        Dim oFilename As String = $"DevExpressGridViewMonitor_UserLayout_Grid{pGridNumber}_Cockpit{COCKPIT_MONITOR_ID}.xml"
        Return System.IO.Path.Combine(USER_CONFIG_DIRECTORY, oFilename)
    End Function

    Private Sub SaveGridLayout(pGridNumber As Integer)
        Try
            Dim oGridView As GridView = Nothing
            Select Case pGridNumber
                Case 1 : oGridView = GridView1
                Case 2 : oGridView = GridView2
                Case 3 : oGridView = GridView3
                Case 4 : oGridView = GridView4
                Case Else
                    LOGGER.Warn($"SaveGridLayout: Invalid grid number [{pGridNumber}]")
                    Exit Sub
            End Select

            oGridView.SaveLayoutToXml(GetGridLayoutPath(pGridNumber), OptionsLayoutBase.FullLayout)
            LOGGER.Debug($"SaveGridLayout: Grid{pGridNumber} layout saved for Cockpit [{COCKPIT_MONITOR_ID}]")
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info($"Error while saving Grid{pGridNumber}Layout: {ex.Message}")
        End Try
    End Sub
    Private Sub LoadGridLayout(pGridNumber As Integer)
        Try
            Dim oXml As String = GetGridLayoutPath(pGridNumber)
            If Not File.Exists(oXml) Then Exit Sub

            Dim oGridView As GridView = Nothing
            Select Case pGridNumber
                Case 1 : oGridView = GridView1
                Case 2 : oGridView = GridView2
                Case 3 : oGridView = GridView3
                Case 4 : oGridView = GridView4
                Case Else
                    LOGGER.Warn($"LoadGridLayout: Invalid grid number [{pGridNumber}]")
                    Exit Sub
            End Select

            oGridView.RestoreLayoutFromXml(oXml, OptionsLayoutBase.FullLayout)
            LOGGER.Debug($"LoadGridLayout: Grid{pGridNumber} layout restored for Cockpit [{COCKPIT_MONITOR_ID}]")
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info($"Error while restoring Grid{pGridNumber}Layout: {ex.Message}")
        End Try
    End Sub
    Private Sub RemoveGridLayout(pGridNumber As Integer)
        Try
            Dim oXml As String = GetGridLayoutPath(pGridNumber)
            If File.Exists(oXml) Then
                IO.File.Delete(oXml)
                LOGGER.Debug($"RemoveGridLayout: Grid{pGridNumber} layout removed for Cockpit [{COCKPIT_MONITOR_ID}]")
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info($"Error while removing Grid{pGridNumber}Layout: {ex.Message}")
        End Try
    End Sub
    Private Sub frmMonitor_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Select Case DT_MONITOR_KONFIG.Rows.Count
            Case 2
                SaveGridLayout(1)
                SaveGridLayout(2)
            Case 3
                SaveGridLayout(1)
                SaveGridLayout(2)
                SaveGridLayout(3)
                CONFIG.Config.MonitorSplitter1_Distance = SplitContainerControl1.SplitterPosition
                CONFIG.Config.MonitorSplitter2_Distance = SplitContainerControl2.SplitterPosition

            Case 4
                SaveGridLayout(1)
                SaveGridLayout(2)
                SaveGridLayout(3)
                SaveGridLayout(4)
                CONFIG.Config.MonitorSplitter1_Distance = SplitContainerControl1.SplitterPosition
                CONFIG.Config.MonitorSplitter2_Distance = SplitContainerControl2.SplitterPosition
                CONFIG.Config.MonitorSplitter3_Distance = SplitContainerControl3.SplitterPosition
        End Select
        CONFIG.Save()
        Try
            DocumentViewerMonitor.Done()
            '_frmDocView.Close()
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub

    Private Sub frmMonitor_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        FormShown = True
        Load_Detail()
        Me.BringToFront()
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        Dim oActiveGrid = GetActiveGridControl()

        If oActiveGrid IsNot Nothing Then


            XtraSaveFileDialog1.FileName = oActiveGrid.Name
            XtraSaveFileDialog1.Filter = "Excel documents (.xlsx)|*.xlsx"
            XtraSaveFileDialog1.DefaultExt = ".xlsx"

            If XtraSaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                Dim oOptions As New XlsxExportOptions() With {
                    .ExportMode = XlsxExportMode.SingleFile
                }
                oActiveGrid.ExportToXlsx(XtraSaveFileDialog1.FileName, oOptions)
            End If
        Else
            MessageBox.Show("Bitte wählen Sie eine Tabelle aus, die Sie exportieren möchten", Text, MessageBoxButtons.OK)
        End If
    End Sub
    Private Function GetActiveGridControl() As GridControl
        If _ActiveGrid Is Nothing Then
            Return Nothing
        End If

        Return _ActiveGrid
    End Function

    Private Sub GridControl1_Enter(sender As Object, e As EventArgs) Handles GridControl1.Enter, GridControl1.Enter, GridControl2.Enter, GridControl3.Enter, GridControl4.Enter
        _ActiveGrid = sender
    End Sub

    Private Sub frmMonitor_HelpButtonClicked(sender As Object, e As CancelEventArgs) Handles Me.HelpButtonClicked

    End Sub

    Private Sub BarButtonItem3_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem3.ItemClick
        If SplitContainerControlMain.Collapsed = True Then
            SplitContainerControlMain.Collapsed = False

            If USER_LANGUAGE = "de-DE" Then
                BarButtonItem3.Caption = "DocView deaktivieren"
            Else
                BarButtonItem3.Caption = "Deactivate DocView"
            End If

            BarButtonItem3.Down = True
            Dim oDocPath
            Try
                oDocPath = GridView1.GetFocusedRowCellValue(GridView1.Columns("FULL_FILE_PATH"))


            Catch ex As Exception
                LOGGER.Warn($"Error getting DocPath in Monitor: {ex.Message}")
                Exit Sub
            End Try
            DocumentViewerMonitor?.LoadFile_FromPath(oDocPath)

            'If oDocPath <> "" Then
            '    If Not Application.OpenForms().OfType(Of frmValidator).Any Then
            '        frmDocView.Show()
            '        _frmDocView = frmDocView
            '    End If
            '    _frmDocView.LoadFile(oDocPath)
            '    Me.SendToBack()
            'End If
        Else
            SplitContainerControlMain.Collapsed = True

            If USER_LANGUAGE = "de-DE" Then
                BarButtonItem3.Caption = "DocView aktivieren"
            Else
                BarButtonItem3.Caption = "Activate DocView"
            End If
            BarButtonItem3.Down = False
        End If

    End Sub

    Private Async Sub BarButtonItem4_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem4.ItemClick
        Select Case DT_MONITOR_KONFIG.Rows.Count
            Case 2
                RemoveGridLayout(1)
                RemoveGridLayout(2)
            Case 3
                RemoveGridLayout(1)
                RemoveGridLayout(2)
                RemoveGridLayout(3)
            Case 4
                RemoveGridLayout(1)
                RemoveGridLayout(2)
                RemoveGridLayout(3)
                RemoveGridLayout(4)
        End Select

        GridView1.ShowLoadingPanel()
        Await Load_Grid_Data()
        GridView1.HideLoadingPanel()
    End Sub
End Class