

Imports System.IO
Imports System.Threading
Imports DevExpress.XtraGrid
Imports DevExpress.XtraPrinting
Imports DevExpress.XtraTab

Public Class frmAdmin2
    Dim oSave As Boolean = True
    Dim DT_FURTHER_KONFIG_VIEW 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 _ActiveGrid As GridControl = Nothing
    Private Sub frmAdmin2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Load_Email_template()
        Load_Gui_Phrases()
        oSave = True
        Try
            Dim oFilename As String = String.Format("DevExLayoutAdmin2_Email.xml")
            Dim oXml As String = System.IO.Path.Combine(USER_CONFIG_DIRECTORY, oFilename)
            If File.Exists(oXml) Then
                DataLayoutControl1.RestoreLayoutFromXml(oXml)
            End If
            oFilename = String.Format("DevExLayoutAdmin2_GUIPhrases.xml")
            oXml = System.IO.Path.Combine(USER_CONFIG_DIRECTORY, oFilename)
            If File.Exists(oXml) Then
                DataLayoutControl2.RestoreLayoutFromXml(oXml)
            End If


        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Error while restoring Datalayout: " & ex.Message)
        End Try

    End Sub
    Sub Status_Changed(text As String)
        labelStatus.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        labelStatus.Caption = $"{text} - {Now.ToLongTimeString}"
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BbitemplateAdd.ItemClick
        TBDD_EMAIL_TEMPLATEBindingSource.AddNew()
        TITLETextEdit.ReadOnly = False
    End Sub



    Private Sub BarButtonItem1_ItemClick_1(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        Load_Email_template()
    End Sub
    Sub Load_Email_template()
        Try
            TBDD_EMAIL_TEMPLATETableAdapter.Connection.ConnectionString = CONNECTION_STRING_ECM
            Me.TBDD_EMAIL_TEMPLATETableAdapter.Fill(Me.DD_DMSLiteDataSet.TBDD_EMAIL_TEMPLATE)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in loading EmailTemplates:")
        End Try
    End Sub
    Sub Load_Gui_Phrases()
        Try
            TBDD_GUI_LANGUAGE_PHRASETableAdapter.Connection.ConnectionString = CONNECTION_STRING_ECM
            Me.TBDD_GUI_LANGUAGE_PHRASETableAdapter.Fill(Me.DD_DMSLiteDataSet.TBDD_GUI_LANGUAGE_PHRASE)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in loading GUIPhrases:")
        End Try
    End Sub
    Private Sub TBDD_EMAIL_TEMPLATEBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBDD_EMAIL_TEMPLATEBindingSource.AddingNew
        DD_DMSLiteDataSet.TBDD_EMAIL_TEMPLATE.ADDED_WHOColumn.DefaultValue = USER_USERNAME
    End Sub

    Private Sub BbitemplateSave_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BbitemplateSave.ItemClick
        Email_Template_Save()
    End Sub
    Sub Email_Template_Save()
        Try
            Me.TBDD_EMAIL_TEMPLATEBindingSource.EndEdit()
            If Not IsNothing(DD_DMSLiteDataSet.TBDD_EMAIL_TEMPLATE.GetChanges) Then
                Me.CHANGED_WHOTextEdit.Text = USER_USERNAME
                Me.TBDD_EMAIL_TEMPLATEBindingSource.EndEdit()
                Me.TBDD_EMAIL_TEMPLATETableAdapter.Update(DD_DMSLiteDataSet.TBDD_EMAIL_TEMPLATE)
                Status_Changed("Vorlage gespeichert")
                TITLETextEdit.ReadOnly = True
            Else
                Status_Changed("Keine Änderung")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Saving EmailTemplates:")
            'MsgBox("Unerwarteter Fehler beim Speichern des Profils: " & vbNewLine & ex.Message, MsgBoxStyle.Critical, Text)
        End Try
    End Sub

    Private Sub BbitemplateDelete_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BbitemplateDelete.ItemClick
        Dim result As MsgBoxResult = MsgBox("Wollen Sie die Vorlage wirklich löschen?", MsgBoxStyle.YesNo, "Bestätigung erforderlich:")
        'wenn Speichern ja
        If result = MsgBoxResult.Yes Then
            Dim oSQL = $"Delete from TBDD_EMAIL_TEMPLATE where guid = {GUIDTextEdit.Text}"
            If DatabaseFallback.ExecuteNonQueryECM(oSQL) = True Then
                Load_Email_template()
                Status_Changed("Vorlage gelöscht!")
            End If
        End If
    End Sub

    Private Sub XtraTabControl1_SelectedPageChanged(sender As Object, e As TabPageChangedEventArgs) Handles XtraTabControl1.SelectedPageChanged
        RibbonPageGroup3.Enabled = True
        RibbonPageGroup4.Enabled = False
        Select Case XtraTabControl1.SelectedTabPageIndex
            Case 0
                RibbonPageGroup1.Enabled = True
                RibbonPageGroup2.Enabled = False
                RibbonPageGroup3.Enabled = False
            Case 1
                RibbonPageGroup2.Enabled = True
                RibbonPageGroup1.Enabled = False
            Case 2
                RibbonPageGroup2.Enabled = False
                RibbonPageGroup1.Enabled = False
                Load_More_Konfig_Grids()
                RibbonPageGroup4.Enabled = True
        End Select
    End Sub
    Private Sub SET_GRID_DESCRIPTION(pGridView As Views.Grid.GridView, pDT As DataTable)
        Dim objectCount_Descr = $"{pGridView.Tag} [{pDT.Rows.Count}] "
        If USER_LANGUAGE = "de-DE" Then
            objectCount_Descr &= " Datensätze"
        ElseIf USER_LANGUAGE = "en-US" Then
            objectCount_Descr &= " records"
        ElseIf USER_LANGUAGE = "fr-FR" Then
        End If
        pGridView.ViewCaption = objectCount_Descr
    End Sub
    Private Sub Load_More_Konfig_Grids()
        Me.Cursor = Cursors.WaitCursor
        Try
            Dim oSQL = "SELECT * FROM TBPM_FURTHER_KONFIG_VIEW"
            DT_FURTHER_KONFIG_VIEW = DatabaseFallback.GetDatatableECM(oSQL) ', "Monitor-Load_Grid_Data1")
            If Not IsNothing(DT_FURTHER_KONFIG_VIEW) Then
                If DT_FURTHER_KONFIG_VIEW.Rows.Count >= 1 Then
                    oSQL = DT_FURTHER_KONFIG_VIEW.Rows(0).Item("GRID_SQL")
                    GridViewWK1.Columns.Clear()
                    Dim oDTGRID1 As DataTable = DatabaseFallback.GetDatatableECM(oSQL) ', "FurtherConfig-Load_Grid_Data1")
                    GridControlWK1.DataSource = oDTGRID1
                    GRID1_TITLE = DT_FURTHER_KONFIG_VIEW.Rows(0).Item("GRID_TITLE")
                    GridViewWK1.Tag = GRID1_TITLE
                    SET_GRID_DESCRIPTION(GridViewWK1, oDTGRID1)
                    spcontwKonfleft.Collapsed = False
                    spcontwKonfRight.Collapsed = False
                    Select Case DT_FURTHER_KONFIG_VIEW.Rows.Count
                        Case 1
                            spcontwKonfRight.Collapsed = True
                        Case 2
                            spcontwKonfleft.Collapsed = True
                            spcontwKonfRight.Collapsed = True
                        Case 3
                            spcontwKonfRight.Collapsed = True
                    End Select
                    If DT_FURTHER_KONFIG_VIEW.Rows.Count > 1 Then
                        GRID2_TITLE = DT_FURTHER_KONFIG_VIEW.Rows(1).Item("GRID_TITLE")
                        GRID2_SQL = DT_FURTHER_KONFIG_VIEW.Rows(1).Item("GRID_SQL")

                        GridViewWK2.Tag = GRID2_TITLE
                        GridViewWK2.Columns.Clear()
                        Dim oDTGRID2 As DataTable = DatabaseFallback.GetDatatableECM(GRID2_SQL) ', "FurtherConfig-Load_Grid_Data2")
                        GridControlWK2.DataSource = oDTGRID2
                        SET_GRID_DESCRIPTION(GridViewWK2, oDTGRID2)
                        Select Case DT_FURTHER_KONFIG_VIEW.Rows.Count
                            Case 3
                                GRID3_TITLE = DT_FURTHER_KONFIG_VIEW.Rows(2).Item("GRID_TITLE")
                                GRID3_SQL = DT_FURTHER_KONFIG_VIEW.Rows(2).Item("GRID_SQL")

                                GridViewWK3.Tag = GRID3_TITLE

                                GridViewWK3.Columns.Clear()
                                Dim oDTGRID3 As DataTable = DatabaseFallback.GetDatatableECM(GRID3_SQL) ', "FurtherConfig-Load_Grid_Data3")
                                GridControlWK3.DataSource = oDTGRID3
                                SET_GRID_DESCRIPTION(GridViewWK3, oDTGRID3)
                            Case 4
                                GRID3_TITLE = DT_FURTHER_KONFIG_VIEW.Rows(2).Item("GRID_TITLE")
                                GRID3_SQL = DT_FURTHER_KONFIG_VIEW.Rows(2).Item("GRID_SQL")
                                GridViewWK3.Tag = GRID3_TITLE
                                GridViewWK3.Columns.Clear()
                                Dim oDTGRID3 As DataTable = DatabaseFallback.GetDatatableECM(GRID3_SQL) ', "FurtherConfig-Load_Grid_Data3")
                                GridControlWK3.DataSource = oDTGRID3
                                SET_GRID_DESCRIPTION(GridViewWK3, oDTGRID3)
                                GRID4_TITLE = DT_FURTHER_KONFIG_VIEW.Rows(3).Item("GRID_TITLE")
                                GRID4_SQL = DT_FURTHER_KONFIG_VIEW.Rows(3).Item("GRID_SQL")
                                GridViewWK4.Tag = GRID4_TITLE
                                GridViewWK4.Columns.Clear()
                                Dim oDTGRID4 As DataTable = DatabaseFallback.GetDatatableECM(GRID4_SQL) ', "FurtherConfig-Load_Grid_Data4")
                                GridControlWK4.DataSource = oDTGRID4
                                SET_GRID_DESCRIPTION(GridViewWK4, oDTGRID4)
                        End Select
                    End If
                End If

            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Load_More_Konfig_Grids:")
        End Try
        Me.Cursor = Cursors.Default
    End Sub


    Private Sub BarButtonItem3_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem3.ItemClick
        GuiPhrase_Save()
    End Sub

    Private Sub BarButtonItem6_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem6.ItemClick
        TBDD_GUI_LANGUAGE_PHRASEBindingSource.AddNew()
    End Sub
    Sub GuiPhrase_Save()
        Try
            Me.TBDD_GUI_LANGUAGE_PHRASEBindingSource.EndEdit()
            If Not IsNothing(DD_DMSLiteDataSet.TBDD_GUI_LANGUAGE_PHRASE.GetChanges) Then
                Me.TextEdit4.Text = USER_USERNAME
                Me.TBDD_GUI_LANGUAGE_PHRASEBindingSource.EndEdit()
                Me.TBDD_GUI_LANGUAGE_PHRASETableAdapter.Update(DD_DMSLiteDataSet.TBDD_GUI_LANGUAGE_PHRASE)
                Status_Changed("Phrase saved!")
            Else
                Status_Changed("No Changes")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Saving GuiPHrase:")

        End Try
    End Sub
    Private Sub BarButtonItem4_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem4.ItemClick

    End Sub

    Private Sub BarButtonItem5_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem5.ItemClick
        Load_Gui_Phrases()
    End Sub

    Private Sub TBDD_GUI_LANGUAGE_PHRASEBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBDD_GUI_LANGUAGE_PHRASEBindingSource.AddingNew
        DD_DMSLiteDataSet.TBDD_GUI_LANGUAGE_PHRASE.ADDED_WHOColumn.DefaultValue = USER_USERNAME
    End Sub



    Private Sub BarButtonItem7_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem7.ItemClick
        Dim oText = EMAIL_BODY1TextEdit.Text
        If EMAIL_BODY2TextEdit.Text <> "" Then
            oText = oText & "<p>" & EMAIL_BODY2TextEdit.Text
        End If
        If EMAIL_BODY3TextEdit.Text <> "" Then
            oText = oText & "<p>" & EMAIL_BODY3TextEdit.Text
        End If
        Dim ofrm As New frmPreviewHtml
        ofrm.DisplayText = oText
        ofrm.ShowDialog()
    End Sub

    Private Sub frmAdmin2_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If oSave = False Then
            Exit Sub
        End If
        Try
            Dim Filename As String = String.Format("DevExLayoutAdmin2_Email.xml")
            Dim xml As String = System.IO.Path.Combine(USER_CONFIG_DIRECTORY, Filename)
            'If File.Exists(xml) Then
            DataLayoutControl1.SaveLayoutToXml(xml)
            'End If
            Filename = String.Format("DevExLayoutAdmin2_GUIPhrases.xml")
            xml = System.IO.Path.Combine(USER_CONFIG_DIRECTORY, Filename)
            DataLayoutControl2.SaveLayoutToXml(xml)
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Error while saving datalayout: " & ex.Message)
        End Try


    End Sub



    Private Sub BarButtonItem8_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem8.ItemClick
        Try
            Dim oFilename = String.Format("DevExLayoutAdmin2_GUIPhrases.xml")
            Dim oXml = System.IO.Path.Combine(USER_CONFIG_DIRECTORY, oFilename)
            File.Delete(oXml)
            MsgBox("Form will now close to reload all controls!", MsgBoxStyle.Information)
            Me.Close()
            oSave = False
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try


    End Sub

    Private Sub BarButtonItem9_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem9.ItemClick
        Try
            Dim oFilename = String.Format("DevExLayoutAdmin2_Email.xml")
            Dim oXml = System.IO.Path.Combine(USER_CONFIG_DIRECTORY, oFilename)
            File.Delete(oXml)
            MsgBox("Form will now close to reload all controls!", MsgBoxStyle.Information)
            Me.Close()
            oSave = False
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub

    Private Sub INTERNALCheckEdit_CheckedChanged_1(sender As Object, e As EventArgs) Handles INTERNALCheckEdit.CheckedChanged
        If INTERNALCheckEdit.Checked Then
            TextEdit2.ReadOnly = True
            OBJ_NAMETextEdit.ReadOnly = True
            STRING1TextEdit.ReadOnly = True
            STRING2TextEdit.ReadOnly = True
        Else
            TextEdit2.ReadOnly = False
            OBJ_NAMETextEdit.ReadOnly = False
            STRING1TextEdit.ReadOnly = False
            STRING2TextEdit.ReadOnly = False
        End If
    End Sub

    Private Sub GridControlWK1_Enter(sender As Object, e As EventArgs) Handles GridControlWK1.Enter, GridControlWK2.Enter, GridControlWK3.Enter, GridControlWK4.Enter, GridControl2.Enter
        _ActiveGrid = sender
    End Sub

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

        If oActiveGrid IsNot Nothing Then


            XtraSaveFileDialog1.FileName = oActiveGrid.Name & ".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 GridViewWK1_ColumnFilterChanged(sender As Object, e As EventArgs) Handles GridViewWK1.ColumnFilterChanged, GridViewWK2.ColumnFilterChanged, GridViewWK3.ColumnFilterChanged, GridViewWK4.ColumnFilterChanged
        Try
            Dim oMyGridView As Views.Grid.GridView = sender
            Dim objectCount_Descr = $"{GridViewWK1.Tag} [{oMyGridView.RowCount.ToString}] "
            If USER_LANGUAGE <> "de-DE" Then
                objectCount_Descr &= " records (filtered)"
            Else
                objectCount_Descr &= " Datensätze (gefiltert)"
            End If
            oMyGridView.ViewCaption = objectCount_Descr
        Catch ex As Exception

        End Try
    End Sub

    Private Sub BarButtonItem11_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem11.ItemClick
        Load_More_Konfig_Grids()
    End Sub
End Class