Imports System.IO
Imports System.Windows.Forms
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.BandedGrid
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Views.Grid
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.ZooFlow
Imports DigitalData.Modules.Language
Imports DevExpress.XtraPrinting
Imports DigitalData.GUIs.Common
Imports System.ComponentModel
Imports DevExpress.XtraGrid.Views.Grid.ViewInfo
Imports DigitalData.Modules.ZooFlow.Constants

Public Class frmDataResultList
    Implements IResultForm

    Private _LogConfig As LogConfig
    Private _Logger As Logger
    Private _Config As ConfigManager(Of DataResultConfig)
    Private _Environment As Environment
    Private _Params As DataResultParams
    Private _ResultLists As List(Of DataResult)
    Private _IsLoading As Boolean

    Private _ActiveGrid As GridControl = Nothing
    Private _ActiveGridBand As GridBand = Nothing
    Private _Helpers As DocumentResultList.Helpers

    Public Property ShouldReturnToPreviousForm As Boolean Implements IResultForm.ShouldReturnToPreviousForm

    Private Property OperationMode As OperationMode Implements IResultForm.OperationMode

    Public Sub New(LogConfig As LogConfig, Environment As Environment, Params As DataResultParams)
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        Dim oConfigPath As String = Path.Combine(Application.UserAppDataPath, "ResultList", Params.WindowGuid)

        _LogConfig = LogConfig
        _Logger = LogConfig.GetLogger()
        _Config = New ConfigManager(Of DataResultConfig)(LogConfig, oConfigPath, Application.StartupPath)
        _Helpers = New DocumentResultList.Helpers(_LogConfig)
        _Environment = Environment
        _Params = Params
        _ResultLists = Params.Results

        ShouldReturnToPreviousForm = False
    End Sub

    Private Sub frmDataResultList_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            ' Load config
            SplitContainerControl1.SplitterPosition = _Config.Config.SplitContainer1Distance
            SwitchMainContainerHorizontal.Checked = _Config.Config.SplitContainer1Horizontal
            SplitContainerControl2.SplitterPosition = _Config.Config.SplitContainer2Distance
            SwitchDetailContainerHorizontal.Checked = _Config.Config.SplitContainer2Horizontal

            If Utils.IsVisibleOnAnyScreen(_Config.Config.WindowLocation) Then
                If Utils.LocationIsVisible(_Config.Config.WindowLocation) Then
                    Location = _Config.Config.WindowLocation
                End If
                If Utils.SizeIsVisible(_Config.Config.WindowSize) Then
                    Size = _Config.Config.WindowSize
                End If
            End If

            AddHandler GridView1.FocusedRowChanged, AddressOf GridView_FocusedRowChanged
            AddHandler GridView2.FocusedRowChanged, AddressOf GridView_FocusedRowChanged
            AddHandler GridView3.FocusedRowChanged, AddressOf GridView_FocusedRowChanged

            Dim oTotalResults = 0

            For Each oList In _ResultLists
                oTotalResults += oList.Datatable.Rows.Count
            Next

            labelResultCount.Caption = String.Format(labelResultCount.Caption, oTotalResults)

            ' Load Grids
            For index = 0 To _ResultLists.Count - 1
                Select Case index
                    Case 0
                        Dim oResult As DataResult = _ResultLists.Item(0)
                        GridBand1.Caption = $"{oResult.Title} ({oResult.Datatable.Rows.Count})"
                        CreateDataGrid(GridView1, oResult.Datatable)

                    Case 1
                        Dim oResult As DataResult = _ResultLists.Item(1)
                        GridBand2.Caption = $"{oResult.Title} ({oResult.Datatable.Rows.Count})"
                        CreateDataGrid(GridView2, oResult.Datatable)

                    Case 2
                        Dim oResult As DataResult = _ResultLists.Item(2)
                        GridBand3.Caption = $"{oResult.Title} ({oResult.Datatable.Rows.Count})"
                        CreateDataGrid(GridView3, oResult.Datatable)

                    Case Else
                        MessageBox.Show(Constants.MESSAGE_TOO_MANY_SEARCHES)
                        Exit For
                End Select
            Next

            ' Hide Grids depending on Result count
            Select Case _ResultLists.Count
                Case 0
                    SplitContainerControl1.SetPanelCollapsed(True)
                    SplitContainerControl2.SetPanelCollapsed(True)

                    SwitchMainContainerHorizontal.Enabled = False
                    SwitchDetailContainerHorizontal.Enabled = False

                    MessageBox.Show(Constants.MESSAGE_ERROR_IN_SEARCHES, Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Case 1
                    SplitContainerControl1.SetPanelCollapsed(True)
                    SplitContainerControl2.SetPanelCollapsed(True)

                    SwitchMainContainerHorizontal.Enabled = False
                    SwitchDetailContainerHorizontal.Enabled = False
                Case 2
                    SplitContainerControl2.SetPanelCollapsed(True)

                    SwitchDetailContainerHorizontal.Enabled = False
            End Select
        Catch ex As Exception
            _Logger.Error(ex)
        Finally
            _IsLoading = False
        End Try
    End Sub

    Private Sub GridView_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs)
        _Helpers.SetRowHandle(e)
    End Sub

    Private Sub GridControl_Enter(sender As GridControl, e As EventArgs) Handles GridControl1.Enter, GridControl2.Enter, GridControl3.Enter
        _ActiveGrid = sender
        SetActiveGridBand()
    End Sub

    Private Sub GridView1_FocusedRowChanged(sender As GridView, e As FocusedRowChangedEventArgs) Handles GridView1.FocusedRowChanged, GridView2.FocusedRowChanged, GridView3.FocusedRowChanged
        Dim oGrid As GridControl = sender.GridControl
        _ActiveGrid = oGrid
    End Sub

    Private Sub SplitContainerControl1_SplitterPositionChanged(sender As Object, e As EventArgs) Handles SplitContainerControl1.SplitterPositionChanged
        If _IsLoading = False Then
            _Config.Config.SplitContainer1Distance = SplitContainerControl1.SplitterPosition
            _Config.Save()
        End If
    End Sub

    Private Sub SplitContainerControl2_SplitterPositionChanged(sender As Object, e As EventArgs) Handles SplitContainerControl2.SplitterPositionChanged
        If _IsLoading = False Then
            _Config.Config.SplitContainer2Distance = SplitContainerControl2.SplitterPosition
            _Config.Save()
        End If
    End Sub

    Public Sub CreateDataGrid(GridView As GridView, Datatable As DataTable)
        GridView.GridControl.DataSource = Datatable
    End Sub

    Private Sub GridView1_ColumnFilterChanged(sender As GridView, e As EventArgs) Handles GridView1.ColumnFilterChanged
        Dim oRowCount = sender.RowCount
        UpdateGridHeader(0, oRowCount)
    End Sub

    Private Sub GridView2_ColumnFilterChanged(sender As GridView, e As EventArgs) Handles GridView2.ColumnFilterChanged
        Dim oRowCount = sender.RowCount
        UpdateGridHeader(1, oRowCount)
    End Sub

    Private Sub GridView3_ColumnFilterChanged(sender As GridView, e As EventArgs) Handles GridView3.ColumnFilterChanged
        Dim oRowCount = sender.RowCount
        UpdateGridHeader(2, oRowCount)
    End Sub

    Private Sub UpdateGridHeader(Index As Integer, Count As Integer)
        Select Case Index
            Case 0
                Dim oResult = _ResultLists.Item(0)
                GridBand1.Caption = $"{oResult.Title} ({Count})"

            Case 1
                Dim oResult = _ResultLists.Item(1)
                GridBand2.Caption = $"{oResult.Title} ({Count})"

            Case 2
                Dim oResult = _ResultLists.Item(2)
                GridBand3.Caption = $"{oResult.Title} ({Count})"
        End Select
    End Sub

    Private Sub SetActiveGridBand()
        If _ActiveGrid.Equals(GridControl1) Then
            _ActiveGridBand = GridBand1
        ElseIf _ActiveGrid.Equals(GridControl2) Then
            _ActiveGridBand = GridBand2
        ElseIf _ActiveGrid.Equals(GridControl3) Then
            _ActiveGridBand = GridBand3
        Else
            _ActiveGridBand = Nothing
        End If
    End Sub

    Private Function GetActiveRow() As DataRow
        Dim oActiveGrid = GetActiveGridControl()
        Dim oActiveRowhandle = _Helpers.ActiveRowHandle

        If oActiveGrid IsNot Nothing And oActiveRowhandle <> Constants.NO_ROW_HANDLE Then
            Dim oView = DirectCast(oActiveGrid.DefaultView, GridView)
            Dim oRow = oView.GetDataRow(oActiveRowhandle)
            Return oRow
        Else
            Return Nothing
        End If
    End Function

    Private Function GetActiveGridControl() As GridControl
        If _ActiveGrid Is Nothing Then
            Return Nothing
        End If

        Return _ActiveGrid
    End Function

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

        If oActiveGrid IsNot Nothing Then
            Dim oGridBand = _ActiveGridBand

            XtraSaveFileDialog.FileName = Utils.ConvertTextToSlug(oGridBand.Caption) & ".xlsx"
            XtraSaveFileDialog.DefaultExt = ".xlsx"

            If XtraSaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
                Dim oOptions As New XlsxExportOptions() With {
                    .ExportMode = XlsxExportMode.SingleFile
                }
                oActiveGrid.ExportToXlsx(XtraSaveFileDialog.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 Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        ShouldReturnToPreviousForm = True
        Close()
    End Sub

    Private Sub SwitchMainContainerHorizontal_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles SwitchMainContainerHorizontal.CheckedChanged
        SplitContainerControl1.Horizontal = SwitchMainContainerHorizontal.Checked

        If _Config IsNot Nothing And _IsLoading = False Then
            _Config.Config.SplitContainer1Horizontal = SwitchMainContainerHorizontal.Checked
            _Config.Save()
        End If
    End Sub

    Private Sub SwitchDetailContainerHorizontal_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles SwitchDetailContainerHorizontal.CheckedChanged
        SplitContainerControl2.Horizontal = SwitchDetailContainerHorizontal.Checked

        If _Config IsNot Nothing And _IsLoading = False Then
            _Config.Config.SplitContainer2Horizontal = SwitchDetailContainerHorizontal.Checked
            _Config.Save()
        End If
    End Sub

    Private Sub frmDataResultList_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        Try
            _Config.Config.WindowLocation = Location
            _Config.Config.WindowSize = Size
            _Config.Save()
        Catch ex As Exception
            _Logger.Error(ex)
        End Try
    End Sub

    Public Function RefreshResults(pResults As IEnumerable(Of BaseResult)) As Boolean Implements IResultForm.RefreshResults
        'TODO: Implement
    End Function


End Class