Imports DevExpress.Utils
Imports DevExpress.XtraEditors.Controls
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraGrid.Views.Grid
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Language.Utils
Imports DigitalData.GUIs.ZooFlow.Administration.ClassConstants
Imports DevExpress.XtraGrid

Public Class frmAdmin_Start
    Private CurrentModule As String
    Private CurrentPage As String
    Private CurrentItem As ClassDetailForm.DetailData

    Private DetailForm As ClassDetailForm

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

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        InitializeBaseForm(My.LogConfig)
    End Sub

    Private Sub frmAdministration_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DetailForm = New ClassDetailForm(My.LogConfig)
        AddHandler DetailForm.DetailFormClosed, AddressOf DetailForm_Closed

        Load_SQLData()
        TreeListMenu.ExpandAll()
    End Sub

    Private Sub DetailForm_Closed(sender As Object, e As IAdminForm)
        If e.HasChanges Then
            Load_SQLData()
            Load_GridData(DetailForm.DetailDataList.Item(CurrentPage))
        End If
    End Sub

    Private Function Handle_LoadPage(Page As String) As Boolean
        If DetailForm.DetailSettingsList.ContainsKey(Page) Then
            Dim oNode = DetailForm.DetailSettingsList.Item(Page)
            CurrentModule = oNode.Module
            labelTitle.Text = oNode.GridTitle
            btnAddRecord.Caption = oNode.NewRecordTitle
            If btnAddRecord.Caption = "" Then
                btnAddRecord.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            Else
                btnAddRecord.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
            End If
        Else
            MsgBox($"Tag [{Page}] not found! Exiting." & vbNewLine &
                   $"Check the [ENTITY_TITLE] Column in Table [TBZF_ADMIN_SOURCE_SQL]. It must match with the Tag [{Page}] of the corresponding Tree List nodes!", MsgBoxStyle.Critical, Text)
            Return False
        End If

        ' This dictionary can contain the same entity multiple times to save
        ' OVERVIEW, INSERT, UPDATE, etc. data records, so we specifically look for the overview key
        Dim oKey = $"{Page}-OVERVIEW"

        If DetailForm.DetailDataList.ContainsKey(oKey) Then

            Dim oItem = DetailForm.DetailDataList.Item(oKey)
            Load_GridData(oItem)
            CurrentItem = oItem
        Else
            MsgBox($"Page [{Page}] not found in AdminItems! Exiting." & vbNewLine &
                   "Check your definitions in the TreeList NodeEditor and in SourceSQL", MsgBoxStyle.Critical, Text)
            Return False
        End If

        Return True
    End Function

    Private Function Load_SQLData() As Boolean
        Try
            Dim oTable As DataTable = My.DatabaseECM.GetDatatable("SELECT * FROM TBZF_ADMIN_SOURCE_SQL WHERE SCOPE = 'OVERVIEW'")
            DetailForm.DetailDataList.Clear()

            For Each oRow As DataRow In oTable.Rows
                Dim oCHeck = oRow.Item("ENTITY_TITLE").ToString
                Dim oItem As New ClassDetailForm.DetailData With {
                    .Guid = CInt(oRow.Item("GUID")),
                    .ParentId = CInt(oRow.Item("PARENT_ID")),
                    .Entity = oRow.Item("ENTITY_TITLE").ToString,
                    .Scope = oRow.Item("SCOPE").ToString,
                    .SQLCommand = oRow.Item("SQL_COMMAND").ToString.Replace("@LANG_CODE", My.Application.User.Language),
                    .PrimaryKey = NotNull(oRow.Item("PK_COLUMN"), String.Empty)
                }

                Try
                    oItem.SQLResult = My.DatabaseECM.GetDatatable(oItem.SQLCommand)
                Catch ex As Exception
                    oItem.SQLResult = Nothing
                    Logger.Error(ex)
                End Try

                Dim oKey As String = oItem.Entity & "-" & oItem.Scope
                DetailForm.DetailDataList.Add(oKey, oItem)
            Next

            Return True
        Catch ex As Exception
            ShowErrorMessage(ex)
            Return False
        End Try
    End Function

    Private Sub TreeListMenu_FocusedNodeChanged(sender As Object, e As DevExpress.XtraTreeList.FocusedNodeChangedEventArgs) Handles TreeListMenu.FocusedNodeChanged
        Try
            If e.Node Is Nothing OrElse e.Node.Tag Is Nothing OrElse e.Node.Tag = String.Empty Then
                RibbonPageGroup1.Enabled = False
                labelTitle.Text = "Start"
                Exit Sub
            End If

            If Handle_LoadPage(e.Node.Tag.ToString) Then
                RibbonPageGroup1.Enabled = True
                CurrentPage = e.Node.Tag.ToString
            End If

        Catch ex As Exception
            ShowErrorMessage(ex)
        End Try
    End Sub

    Private Sub Style_ActiveColumn(ActiveColumn As GridColumn)
        Dim oActiveEditor As New RepositoryItemImageComboBox With {
            .SmallImages = ActiveImages,
            .GlyphAlignment = HorzAlignment.Center
        }
        oActiveEditor.Buttons.Clear()
        oActiveEditor.Items.AddRange(New List(Of ImageComboBoxItem) From {
            New ImageComboBoxItem("Active", True, 0),
            New ImageComboBoxItem("Inactive", False, 1)
        })

        With ActiveColumn
            .Caption = " "
            .Name = "columnActive"
            .Visible = True
            .VisibleIndex = 0
            .ColumnEdit = oActiveEditor
            .MaxWidth = 30
            .MinWidth = 30
            .Image = ActiveImages.GetImage(0)
            .OptionsColumn.AllowEdit = False
        End With
    End Sub

    Private Sub Load_GridData(Source As ClassDetailForm.DetailData)
        If Source Is Nothing OrElse Source.SQLResult Is Nothing Then
            Exit Sub
        End If

        ViewMain.ShowLoadingPanel()
        Source.SQLResult = My.DatabaseECM.GetDatatable(Source.SQLCommand)
        GridMain.DataSource = Source.SQLResult
        GridMain.ForceInitialize()
        ViewMain.PopulateColumns()

        If ViewMain.Columns.Item(COLUMN_NAME_ACTIVE) Is Nothing Then
            Dim oActiveColumn = New GridColumn() With {.FieldName = COLUMN_NAME_ACTIVE}
            ViewMain.Columns.Add(oActiveColumn)
            Style_ActiveColumn(oActiveColumn)
        Else
            Style_ActiveColumn(ViewMain.Columns.Item(COLUMN_NAME_ACTIVE))
        End If

        With ViewMain.Appearance.EvenRow
            .BackColor = Color.Snow
            .Options.UseBackColor = True
        End With

        With ViewMain.Appearance.FocusedCell
            .BackColor = Color.Gold
            .Options.UseBackColor = True
        End With

        With ViewMain.OptionsBehavior
            .Editable = False
            .ReadOnly = True
        End With

        With ViewMain.OptionsView
            .ShowAutoFilterRow = True
            .EnableAppearanceEvenRow = True
            .ShowIndicator = False
            .ShowHorizontalLines = DefaultBoolean.True
            .ShowVerticalLines = DefaultBoolean.True
        End With

        With ViewMain.OptionsClipboard
            .CopyColumnHeaders = DefaultBoolean.False
        End With

        With ViewMain.OptionsFind
            .AlwaysVisible = True
        End With

        AddHandler ViewMain.KeyDown, AddressOf GridView1_KeyDown

        ViewMain.BestFitColumns()
        ViewMain.HideLoadingPanel()
    End Sub

    Public Sub GridView1_KeyDown(sender As GridView, e As KeyEventArgs)
        Dim oView As GridView = sender
        If e.Control AndAlso e.KeyCode = Keys.C And e.Modifiers = Keys.Control Then
            Dim oCellValue = oView.GetRowCellValue(oView.FocusedRowHandle, oView.FocusedColumn)
            If oCellValue IsNot Nothing AndAlso oCellValue.ToString() <> String.Empty Then
                Clipboard.SetText(oCellValue.ToString)
            End If
            e.Handled = True
        End If
    End Sub

    Private Sub GridView1_RowClick(sender As Object, e As RowClickEventArgs) Handles ViewMain.RowClick
        Try
            If e.Clicks = 2 And e.Button = MouseButtons.Left Then
                Dim oPrimaryKey = Get_PrimaryKey(e.RowHandle)

                If oPrimaryKey IsNot Nothing Then
                    DetailForm.Handle_OpenDetail(oPrimaryKey, CurrentPage, False)
                Else
                    Throw New ArgumentNullException("PrimaryKey")
                End If
            End If
        Catch ex As Exception
            ShowErrorMessage(ex)
        End Try
    End Sub

    Private Function Get_PrimaryKey(RowHandle As Integer)
        Try
            Dim oView As GridView = ViewMain
            Dim oRowView As DataRowView = oView.GetRow(RowHandle)
            Dim oItem As ClassDetailForm.DetailData = CurrentItem
            Dim oGuid = oRowView.Row.Item(oItem.PrimaryKey)

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

    Private Sub BarButtonItem9_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem9.ItemClick
        Load_SQLData()
        ShowStatus("Source SQL neu geladen")
    End Sub

    Private Sub ShowStatus(v As String)
        labelStatus.Caption = v
        labelStatus.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
    End Sub

    Private Sub ResetStatus()
        labelStatus.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
    End Sub

    Private Sub btnAddRecord_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnAddRecord.ItemClick
        Try
            DetailForm.Handle_OpenDetail(Nothing, CurrentPage, True)
        Catch ex As Exception
            ShowErrorMessage(ex)
        End Try
    End Sub

    Private Sub btnEditRecord_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnEditRecord.ItemClick
        Try
            If ViewMain.FocusedRowHandle = GridControl.InvalidRowHandle Then
                Exit Sub
            End If

            Dim oPrimaryKey = Get_PrimaryKey(ViewMain.FocusedRowHandle)

            If oPrimaryKey IsNot Nothing Or CurrentPage = PAGE_GI_RELATIONS Then
                DetailForm.Handle_OpenDetail(oPrimaryKey, CurrentPage, False)
            End If
        Catch ex As Exception
            Logger.Error(ex)
        End Try
    End Sub
End Class