Imports System.Drawing.Imaging
Imports System.IO
Imports DevExpress.XtraCharts
Imports DevExpress.XtraGrid.Views.Tile
Imports DigitalData.GUIs.Common

Partial Public Class frmInvDashboard
    Private _selectedChart As ChartControl
    Private Sub frmInvDashboard_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Dim oGridBuilder As New GridBuilder(GridView1)
            oGridBuilder.
                WithDefaults().
                WithReadOnlyOptions().
                WithClipboardHandler()

            Try

                VWPM_CHART_INVOICE_MONITOR_SERIESTableAdapter.Connection.ConnectionString = CONNECTION_STRING_ECM
                Me.VWPM_CHART_INVOICE_MONITOR_SERIESTableAdapter.Fill(Me.DD_DMSLiteDataSet.VWPM_CHART_INVOICE_MONITOR_SERIES, COCKPIT_CHART_ID)
            Catch ex As Exception
                MsgBox("Error loading VWPM_CHART_INVOICE_MONITOR_SERIES - " & ex.Message, MsgBoxStyle.Exclamation, ADDITIONAL_TITLE)
                LOGGER.Error(ex)
            End Try
            Try
                Dim osql = $"SELECT KRED_NAME, ANZ_BELEG, Netto, Skonto FROM VWPM_CHART_TOP5 WHERE COCKPIT_CHART_ID = {COCKPIT_CHART_ID}"
                Dim dtTOP5 As DataTable = DatabaseFallback.GetDatatableECM(osql)
                If IsNothing(dtTOP5) OrElse dtTOP5.Rows.Count = 0 Then
                    LOGGER.Warn("No data for VWPM_CHART_TOP5 - check SQL query or connection!")
                    GridControlTopKreditoren.DataSource = Nothing
                    GridControlTopKreditoren.Visible = False
                    BarButtonItemTKredPdf.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                    BarButtonItemTKredExcel.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                Else
                    GridControlTopKreditoren.DataSource = dtTOP5
                    GridControlTopKreditoren.Visible = True
                    BarButtonItemTKredPdf.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                    BarButtonItemTKredExcel.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                End If

                'VWPM_CHART_TOP5TableAdapter.Connection.ConnectionString = CONNECTION_STRING_ECM
                'Me.VWPM_CHART_TOP5TableAdapter.Fill(Me.DD_DMSLiteDataSet.VWPM_CHART_TOP5, COCKPIT_CHART_ID)
            Catch ex As Exception
                MsgBox("Error loading VWPM_CHART_TOP5 - " & ex.Message, MsgBoxStyle.Exclamation, ADDITIONAL_TITLE)
                LOGGER.Error(ex)
            End Try
            ApplySplitterPosition()
            Layout_Dashboard()

        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Error loading form2 - " & ex.Message, MsgBoxStyle.Exclamation, ADDITIONAL_TITLE)
        End Try
    End Sub
    Private Sub frmInvDashboard_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        SaveSplitterPosition()
    End Sub
    Private Sub ApplySplitterPosition()
        Try
            If IsNothing(CONFIG) OrElse IsNothing(CONFIG.Config) Then
                Return
            End If

            If IsNothing(CONFIG.Config.InvDashboardSplitterPositions) Then
                CONFIG.Config.InvDashboardSplitterPositions = New List(Of ClassConfig.InvDashboardSplitterPosition)
                Return
            End If

            Dim entry = CONFIG.Config.InvDashboardSplitterPositions.
            FirstOrDefault(Function(x) x.CockpitChartId = COCKPIT_CHART_ID)

            If entry IsNot Nothing Then
                SplitContainerControl1.SplitterPosition = entry.SplitterPosition
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try

    End Sub

    Private Sub SaveSplitterPosition()
        Try
            If IsNothing(CONFIG) OrElse IsNothing(CONFIG.Config) Then
                Return
            End If

            If IsNothing(CONFIG.Config.InvDashboardSplitterPositions) Then
                CONFIG.Config.InvDashboardSplitterPositions = New List(Of ClassConfig.InvDashboardSplitterPosition)
            End If

            Dim entry = CONFIG.Config.InvDashboardSplitterPositions.
            FirstOrDefault(Function(x) x.CockpitChartId = COCKPIT_CHART_ID)

            If entry Is Nothing Then
                CONFIG.Config.InvDashboardSplitterPositions.Add(New ClassConfig.InvDashboardSplitterPosition With {
                .CockpitChartId = COCKPIT_CHART_ID,
                .SplitterPosition = SplitContainerControl1.SplitterPosition
            })
            Else
                entry.SplitterPosition = SplitContainerControl1.SplitterPosition
            End If
            CONFIG.Save()
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try

    End Sub
    Sub Layout_Dashboard()
        Try
            Dim groupCount As Integer
            Dim charts As List(Of ChartControl)
            Dim oGroups As DataRow() = BASEDATA_DT_CHARTS.Select($"COCKPIT_CHART_ID = {COCKPIT_CHART_ID}")
            groupCount = oGroups.Count


            Configure_Split_Containers(groupCount)
            charts = New List(Of ChartControl) From {ChartTopLeft, ChartTopRight, ChartBottomLeft, ChartBottomRight}
            If groupCount >= 1 Then
                LOGGER.Debug($"ChartCreating...Found {groupCount} ChartKonfigs")
                SplitContainerDashboard.Visible = True
                RibbonPageGroup1.Visible = True
                RibbonPageGroup1.Enabled = False
                SplitContainerControl1.Collapsed = False
            Else
                SplitContainerDashboard.Visible = False
                RibbonPageGroup1.Visible = False
                SplitContainerControl1.Collapsed = True
                LOGGER.Debug($"ChartCreating...No chart-Configuration!! BASEDATA_DT_CHARTS = 0")
                Exit Sub
            End If
            If groupCount >= 1 Then
                LOGGER.Debug($"ChartCreating...Found more than one charts [{groupCount}]")
                For Each gRow As DataRow In oGroups
                    Dim oGroupIndex As Integer = Array.IndexOf(oGroups, gRow)
                    Dim oGroupID As String = gRow.Item("GROUP_ID")

                    Dim groupCharts = BASEDATA_DT_CHARTS.Select(String.Format("GROUP_ID = '{0}'", oGroupID))
                    Dim chart As ChartControl

                    For Each cRow As DataRow In groupCharts

                        Dim oChartType = cRow.Item("TYPE_CHART")
                        LOGGER.Debug($"oChartType [{oChartType}]")
                        Dim oChartTitle = cRow.Item("TITLE")
                        LOGGER.Debug($"oChartTitle [{oChartTitle}]")
                        Dim guid = cRow.Item("GUID")
                        LOGGER.Debug($"guid [{guid}]")
                        Dim oChartValue = cRow.Item("VALUE")
                        Dim oChartArgument = cRow.Item("ARGUMENT")
                        Dim oSqlchart = cRow.Item("SQL_COMMAND")
                        oSqlchart = oSqlchart.Replace("@USER", USER_USERNAME)
                        Dim DATA_DT As DataTable = DatabaseFallback.GetDatatableECM(oSqlchart) ', "layputDashboard1")

                        Dim series As Series = Create_Series(oChartTitle, oChartType.ToString.ToUpper)

                        ' Select Current Chart
                        chart = Select_Chart(oGroupIndex)
                        chart = charts.Item(oGroupIndex)
                        Try
                            chart.Series.Clear()
                        Catch ex As Exception
                            LOGGER.Error(ex)

                        End Try
                        ' Set DataSource
                        chart.DataSource = DATA_DT

                        ' Set shown Columns for Chart
                        series.ArgumentDataMember = oChartArgument
                        series.ValueDataMembers.AddRange(New String() {oChartValue})

                        'set some options
                        chart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.True

                        ' Show Data
                        chart.Series.Add(series)

                    Next ' End Charts
                Next 'End Groups
            Else
                ' Create Charts
                For Each cRow As DataRow In BASEDATA_DT_CHARTS.Rows

                    Dim chart As ChartControl

                    Dim chartIndex As Integer = BASEDATA_DT_CHARTS.Rows.IndexOf(cRow)

                    Dim oChartType = cRow.Item("TYPE_CHART")
                    Dim oChartTitle = cRow.Item("TITLE")
                    Dim guid = cRow.Item("GUID")
                    Dim oChartValue = cRow.Item("VALUE")
                    Dim oChartArgument = cRow.Item("ARGUMENT")
                    Dim oSqlchart = cRow.Item("SQL_COMMAND")

                    oSqlchart = clsPatterns.ReplaceInternalValues(oSqlchart)
                    oSqlchart = clsPatterns.ReplaceUserValues(oSqlchart)

                    oSqlchart = oSqlchart.ToString.ToUpper.Replace("@USER_ID", USER_ID)
                    oSqlchart = oSqlchart.ToString.ToUpper.Replace("@USER", USER_USERNAME)
                    Dim DATA_DT As DataTable = DatabaseFallback.GetDatatableECM(oSqlchart) ', "layputDashboard2")

                    ' Create Series based on type
                    Dim series As Series = Create_Series(oChartTitle, oChartType)

                    ' Select Current Chart
                    chart = Select_Chart(chartIndex)
                    Try
                        chart.Series.Clear()
                    Catch ex As Exception
                        LOGGER.Error(ex)

                    End Try
                    ' Set DataSource
                    chart.DataSource = DATA_DT

                    ' Set shown Columns for Chart
                    series.ArgumentDataMember = oChartArgument
                    series.ValueDataMembers.AddRange(New String() {oChartValue})

                    'set some options
                    chart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.True
                    chart.OptionsPrint.SizeMode = Printing.PrintSizeMode.Stretch

                    ' Show Data
                    chart.Series.Add(series)

                Next
            End If

        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Layout Dashboard - Error: " & ex.Message)
            MsgBox("Unexpected Error in Layout Dashboard - Error: " & vbNewLine & ex.Message, MsgBoxStyle.Critical, ADDITIONAL_TITLE)
        End Try
    End Sub
    Private Sub Configure_Split_Containers(VisibleContainers As Integer)
        Select Case VisibleContainers
            Case 1
                ' Show only ChartTopLeft
                SplitContainerTop.Panel2Collapsed = True
                ' Collapse SplitContainerBottom
                SplitContainerDashboard.Panel2Collapsed = True
            Case 2
                ' Collapse SplitContainerBottom
                SplitContainerDashboard.Panel2Collapsed = True
            Case 3
                ' Collapse ChartBottomRight
                SplitContainerBottom.Panel2Collapsed = True
                ' Show SplitContainerBottom
                SplitContainerDashboard.Panel2Collapsed = False
            Case 4
                ' Show SplitContainerBottom
                SplitContainerDashboard.Panel2Collapsed = False
        End Select
        SplitContainerDashboard.Dock = DockStyle.Fill
    End Sub
    Private Function Select_Chart(index As Integer)
        Select Case index
            Case 0
                Return ChartTopLeft
            Case 1
                Return ChartTopRight
            Case 2
                Return ChartBottomLeft
            Case Else
                Return ChartBottomRight
        End Select
    End Function
    Private Function Create_Series(title As String, type As String) As Series
        Dim series As Series
        LOGGER.Debug($"In Create new series: type [{type}]")
        Select Case type
            Case "BAR"
                LOGGER.Debug("Create new series: ViewType.Bar")
                series = New Series(title, ViewType.Bar)
            Case "LINE"
                LOGGER.Debug("Create new series: ViewType.Line")
                series = New Series(title, ViewType.Line)
            Case "AREA"
                LOGGER.Debug("Create new series: ViewType.Area")
                series = New Series(title, ViewType.Area)
            Case "DOUGHNUT"
                LOGGER.Debug("Create new series: ViewType.Doughnut")
                series = New Series(title, ViewType.Doughnut)
                series.Label.TextPattern = "{A}: {VP:p0}"
                Dim view As PieSeriesView = DirectCast(series.View, PieSeriesView)
                view.Titles.Add(New SeriesTitle())
                view.Titles(0).Text = title
            Case "PIE"
                LOGGER.Debug("Create new series: ViewType.Pie")
                series = New Series(title, ViewType.Pie)
                series.Label.TextPattern = "{A}: {VP:p0}"
                Dim view As PieSeriesView = DirectCast(series.View, PieSeriesView)
                view.Titles.Add(New SeriesTitle())
                view.Titles(0).Text = title
            Case Else
                series = New Series(title, ViewType.Bar)
        End Select

        Return series
    End Function
    Private Sub TileView1_ItemCustomize(sender As Object, e As DevExpress.XtraGrid.Views.Tile.TileViewItemCustomizeEventArgs) Handles TileView1.ItemCustomize
        Dim oView As TileView = sender
        Dim ovalue = oView.GetRowCellValue(e.RowHandle, "Title")
        If ovalue = "Alle Rechnungen" Then
            e.Item.AppearanceItem.Normal.BackColor = Color.Blue
            'e.Item.Elements(1).Text = ""
            e.Item.Elements(0).Appearance.Normal.ForeColor = Color.White
            e.Item.Elements(1).Appearance.Normal.ForeColor = Color.White
            e.Item.Elements(2).Appearance.Normal.ForeColor = Color.White
            'Console.WriteLine("")
        ElseIf ovalue = "Zeitkritisch" Then
            e.Item.Elements(0).Appearance.Normal.ForeColor = Color.Red
            e.Item.Elements(1).Appearance.Normal.ForeColor = Color.Red
            e.Item.Elements(2).Appearance.Normal.ForeColor = Color.Red
        End If
    End Sub

    Private Sub ChartTopLeft_Click(sender As Object, e As EventArgs) Handles ChartTopLeft.Click, ChartTopRight.Click, ChartBottomLeft.Click, ChartBottomRight.Click
        _selectedChart = sender
        RibbonPageGroup1.Enabled = True
        RibbonPageGroup2.Enabled = False
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        If Not IsNothing(_selectedChart) Then
            SaveFileDialog1.Filter = "PDF Files (*.pdf*)|*.pdf"
            If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                ExportChart2Pdf(_selectedChart, SaveFileDialog1.FileName)
            End If
        Else
            MsgBox("Please select a chart via clicking on it!", MsgBoxStyle.Information, ADDITIONAL_TITLE)
        End If
    End Sub
    Sub ExportChart2Pdf(pMyChart As ChartControl, pFilePath As String)
        Try
            pMyChart.OptionsPrint.ImageFormat = DevExpress.XtraCharts.Printing.PrintImageFormat.Metafile
            pMyChart.ExportToPdf(pFilePath, New DevExpress.XtraPrinting.PdfExportOptions With {
                .ConvertImagesToJpeg = False
            })
            ' Exports to a stream as PDF. 
            Dim pdfStream As FileStream = New FileStream(pFilePath, FileMode.Create)
            pMyChart.ExportToPdf(pdfStream)
            ' ... 
            pdfStream.Close()
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub
    Sub ExportCharttoimage(pMyChart As ChartControl, pFilePath As String)
        Try
            SaveChartImageToFile(pMyChart, ImageFormat.Png, pFilePath)
            Dim image As Image = GetChartImage(pMyChart, ImageFormat.Png)
            image.Save(pFilePath)
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try

    End Sub
    Private Sub SaveChartImageToFile(ByVal chart As ChartControl, ByVal format As ImageFormat, ByVal fileName As String)
        ' Create an image in the specified format from the chart  
        ' and save it to the specified path.  
        chart.ExportToImage(fileName, format)
    End Sub
    Private Function GetChartImage(ByVal chart As ChartControl, ByVal format As ImageFormat) As Image
        ' Create an image.  
        Dim image As Image = Nothing

        ' Create an image of the chart.  
        Using s As New MemoryStream()
            chart.ExportToImage(s, format)
            image = System.Drawing.Image.FromStream(s)
        End Using

        ' Return the image.  
        Return image
    End Function

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        If Not IsNothing(_selectedChart) Then
            SaveFileDialog1.Filter = "PNG Files(* .png *)|*.png"
            If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                ExportCharttoimage(_selectedChart, SaveFileDialog1.FileName)
            End If
        Else
            MsgBox("Please select a chart via clicking on it!", MsgBoxStyle.Information, ADDITIONAL_TITLE)
        End If

    End Sub

    Private Sub GridControl1_Click(sender As Object, e As EventArgs) Handles GridControl1.Click
        RibbonPageGroup1.Enabled = False
        RibbonPageGroup2.Enabled = True
        BarButtonItem3.Enabled = True
        BarButtonItemTKredExcel.Enabled = False
        BarButtonItemTKredPdf.Enabled = False
    End Sub

    Private Sub BarButtonItem3_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem3.ItemClick
        SaveFileDialog1.Filter = "PDF Files (*.pdf*)|*.pdf"
        If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            TileView1.ExportToPdf(SaveFileDialog1.FileName)
        End If
    End Sub

    Private Sub BarButtonItem4_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemTKredExcel.ItemClick
        SaveFileDialog1.Filter = "Excel Files (*.xlsx*)|*.xlsx"
        If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            GridView1.ExportToXlsx(SaveFileDialog1.FileName)
        End If
    End Sub

    Private Sub BarButtonItem5_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemTKredPdf.ItemClick
        SaveFileDialog1.Filter = "PDF Files (*.pdf*)|*.pdf"
        If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            GridView1.ExportToPdf(SaveFileDialog1.FileName)
        End If
    End Sub

    Private Sub GridControl2_Click(sender As Object, e As EventArgs) Handles GridControlTopKreditoren.Click
        RibbonPageGroup1.Enabled = False
        RibbonPageGroup2.Enabled = True
        BarButtonItem3.Enabled = False
        BarButtonItemTKredExcel.Enabled = True
        BarButtonItemTKredPdf.Enabled = True
    End Sub

    Private Sub frmInvDashboard_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        Me.BringToFront()
    End Sub
End Class