Imports DevExpress.Utils
Imports System.Text
Imports System.IO

Public Class frmGlobalSearch
    Inherits Form
    Dim sel_Records, sel_FT As String
    Private Sub tsbtnRefresh_Click(sender As Object, e As EventArgs) Handles tsbtnRefresh.Click
        Refresh_Search()
    End Sub
    Sub Refresh_Search()
        If txtSearch.Text = "" Then
            Exit Sub
        End If
        sel_Records = ""
        sel_FT = ""

        If rbSearchCombined.Checked = True Then
            PREPARE_RECORD_SQL()
            PREPARE_FT_SQL()
        End If
        If rbSearchRecord.Checked = True Then
            PREPARE_RECORD_SQL()
        End If
        If rbSearchFulltext.Checked Then
            PREPARE_FT_SQL()
        End If
        Dim DT_Files As DataTable
        Dim DT_RECORD_RESULT As DataTable
        If rbSearchCombined.Checked Or rbSearchRecord.Checked Then
            DT_RECORD_RESULT = Refresh_Records()
        Else
            SplitContainerMain.CollapsePanel = DevExpress.XtraEditors.SplitCollapsePanel.Panel1
            SplitContainerMain.Collapsed = True
            tslblRecordsResult.Text = String.Format("No records found")
            GridControlRecords.DataSource = Nothing
        End If
        If rbSearchCombined.Checked Or rbSearchFulltext.Checked Then
            DT_Files = Refresh_Files()
            If rbSearchFulltext.Checked Then
                SplitContainerMain.CollapsePanel = DevExpress.XtraEditors.SplitCollapsePanel.Panel1
                SplitContainerMain.Collapsed = True
            End If
        Else
            SplitContainerMain.CollapsePanel = DevExpress.XtraEditors.SplitCollapsePanel.Panel2
            SplitContainerMain.Collapsed = True
            GridControlFiles.DataSource = Nothing
        End If
    End Sub
    Sub PREPARE_FT_SQL()
        Dim sqlft = SQL_FULLTEXT
        sqlft = sqlft.Replace("@FULLTEXT", txtSearch.Text)
        Dim selDoc = String.Format("SELECT [DocID],[FULL_FILENAME],[Filename],[DISPLAY_NAME],[Doctype],[Creation_DateTime] As CreatedWhen,[Change_DateTime] as ChangedWhen,[IN_WORK] as [InWork?] " & _
                    "FROM VWPMO_DOC_SEARCH where DocID in " & vbNewLine & _
                    "({0}) " & vbNewLine & _
                    "AND DocID IN (SELECT dwObjectID FROM VWPMO_WD_OBJECT_RIGHTS WHERE dwUserOrGroupID = {1})", sqlft, USERID_FK_INT_ECM)
        sel_FT = selDoc

    End Sub
    Sub PREPARE_RECORD_SQL()
        sel_Records = String.Format("select T.RECORD_ID,TR.FORM_ID AS ENTITY_ID ,[dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), TFV.GUID), 1) as Entity," & _
                                       "T.VALUE,TR.ADDED_WHO as AddedWho,TR.ADDED_WHEN as AddedWhen,TR.CHANGED_WHO As ChangedWho,TR.CHANGED_WHEN as ChangedWhen from TBPMO_CONTROL_VALUE T,TBPMO_RECORD TR,TBPMO_FORM_VIEW TFV " & _
                                       "where T.RECORD_ID = TR.GUID AND TR.FORM_ID = TFV.FORM_ID AND T.value like '%{1}%' ORDER BY T.RECORD_ID", USER_LANGUAGE, txtSearch.Text)
    End Sub
    Private Function Refresh_Records()
        Dim DT_RECORD_RESULT = ClassDatabase.Return_Datatable(sel_Records)
        If Not IsNothing(DT_RECORD_RESULT) Then
            SplitContainerMain.CollapsePanel = DevExpress.XtraEditors.SplitCollapsePanel.None
            SplitContainerMain.Collapsed = False
            If DT_RECORD_RESULT.Rows.Count > 0 Then
                GridControlRecords.DataSource = DT_RECORD_RESULT
                tslblRecordsResult.Text = String.Format("{0} records found", DT_RECORD_RESULT.Rows.Count)
                Try
                    GridViewRecords.Columns("AddedWhen").DisplayFormat.FormatType = FormatType.DateTime
                    GridViewRecords.Columns("AddedWhen").DisplayFormat.FormatString = CURRENT_DATE_FORMAT & " HH:MM:ss"
                    GridViewRecords.Columns("ChangedWhen").DisplayFormat.FormatType = FormatType.DateTime
                    GridViewRecords.Columns("ChangedWhen").DisplayFormat.FormatString = CURRENT_DATE_FORMAT & " HH:MM:ss"
                    GridViewRecords.ApplyFindFilter(txtSearch.Text)
                Catch ex As Exception

                End Try
                ' FormID und RecordID immer ausblenden
                GridViewRecords.Columns.Item("ENTITY_ID").Visible = False
            Else
                tslblRecordsResult.Text = String.Format("No records found")
                GridControlRecords.DataSource = Nothing
            End If
            Return DT_RECORD_RESULT
        Else
            Return Nothing
        End If
    End Function
    Private Function Refresh_Files()
        Dim DT_Files = ClassDatabase.Return_Datatable(sel_FT, True)
        If Not IsNothing(DT_Files) Then
            SplitContainerMain.CollapsePanel = DevExpress.XtraEditors.SplitCollapsePanel.None
            SplitContainerMain.Collapsed = False
            If DT_Files.Rows.Count > 0 Then
                GridControlFiles.DataSource = DT_Files
                tslblDocView.Text = String.Format("{0} files found", DT_Files.Rows.Count)
                Try
                    GridViewFiles.Columns("AddedWhen").DisplayFormat.FormatType = FormatType.DateTime
                    GridViewFiles.Columns("AddedWhen").DisplayFormat.FormatString = CURRENT_DATE_FORMAT & " HH:MM:ss"
                    GridViewFiles.Columns("ChangedWhen").DisplayFormat.FormatType = FormatType.DateTime
                    GridViewFiles.Columns("ChangedWhen").DisplayFormat.FormatString = CURRENT_DATE_FORMAT & " HH:MM:ss"
                Catch ex As Exception

                End Try
                ' FormID und RecordID immer ausblenden
                GridViewFiles.Columns.Item("FULL_FILENAME").Visible = False
            Else
                tslblDocView.Text = String.Format(" No files found")
                GridControlFiles.DataSource = Nothing
            End If
            Return DT_Files
        Else
            Return Nothing
        End If
    End Function

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        Export_Excel(GridControlRecords)
    End Sub

    Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
        Export_Excel(GridControlFiles)
    End Sub

    Private Sub ExportExcelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExportExcelToolStripMenuItem.Click
        Export_Excel(GridControlRecords)
    End Sub
    Sub Export_Excel(Grid As DevExpress.XtraGrid.GridControl)
        Dim saveFileDialog1 As New SaveFileDialog
        saveFileDialog1.Filter = "Excel File|*.xlsx"
        saveFileDialog1.Title = "Export to Excel:"
        saveFileDialog1.ShowDialog()
        If saveFileDialog1.FileName <> "" Then
            Cursor = Cursors.WaitCursor
            Grid.MainView.ExportToXlsx(saveFileDialog1.FileName)
            Dim result As MsgBoxResult
            Dim msg = String.Format("Datei wurde erstellt! Wollen Sie diese nun öffnen?")

            If USER_LANGUAGE <> "de-DE" Then
                msg = String.Format("File was created. Do You want to open excel?")
            End If
            result = MessageBox.Show(msg, "Exporting result:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                Process.Start(saveFileDialog1.FileName)
            End If
        End If
        Cursor = Cursors.Default
    End Sub

    Private Sub ShowRecordToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ShowRecordToolStripMenuItem.Click
        Show_Detail_Record()
    End Sub
    Sub Show_Detail_Record()
        Try
            Dim RECORD_ID = GridViewRecords.GetFocusedRowCellValue(GridViewRecords.Columns("RECORD_ID"))
            If Not IsNothing(RECORD_ID) Then
                ClassJumpRecord.JumpToRecord(0, RECORD_ID)
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in Show_Detail_Record:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
        JUMP_RECORD_ID = 0
    End Sub

    Private Sub frmSearchAllOVer_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Save_DocGrid_Layout()
        Save_RecGrid_Layout()
    End Sub
    Private Sub frmSearchAllOVer_KeyUp(sender As Object, e As KeyEventArgs) Handles MyBase.KeyUp
        If e.KeyCode = Keys.Return Then
            Refresh_Search()
        End If
    End Sub

    Private Sub tsbtnviewDetail_Click(sender As Object, e As EventArgs) Handles tsbtnviewDetail.Click
        Show_Detail_Record()
    End Sub

    Private Sub GridControlFiles_DoubleClick(sender As Object, e As EventArgs) Handles GridControlFiles.DoubleClick
        Me.Cursor = Cursors.WaitCursor

        For Each row In GridViewFiles.GetSelectedRows
            Dim SELECTED_DOC_PATH = GridViewFiles.GetRowCellValue(row, "FULL_FILENAME")
            Dim SELECTED_DOC_ID = GridViewFiles.GetRowCellValue(row, "DocID")
            If IsNothing(SELECTED_DOC_PATH) Then
                MsgBox("Could not read File Parameters!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If

            ClassHelper.File_open(SELECTED_DOC_PATH, SELECTED_DOC_ID)

        Next
        Me.Cursor = Cursors.Default
    End Sub
    Sub Save_DocGrid_Layout()
        Try
            Dim XMLPath = Get_DocGrid_Layout_Filename()
            GridViewFiles.SaveLayoutToXml(XMLPath)
            ' Update_Status_Label(True, "Grid Layout Loaded")
        Catch ex As Exception
            MsgBox("Error in Save_DocGrid_Layout:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Sub Save_RecGrid_Layout()
        Try
            Dim XMLPath = Get_RecordGrid_Layout_Filename()
            GridViewRecords.SaveLayoutToXml(XMLPath)
            ' Update_Status_Label(True, "Grid Layout Loaded")
        Catch ex As Exception
            MsgBox("Error in Save_RecGrid_Layout:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Sub Load_DocGrid_Layout()
        Try
            Dim XMLPath = Get_DocGrid_Layout_Filename()
            If File.Exists(XMLPath) Then
                GridViewFiles.RestoreLayoutFromXml(XMLPath)
                GridViewFiles.GuessAutoFilterRowValuesFromFilter()
            End If

        Catch ex As Exception
            MsgBox("Error in Load_DocGrid_Layout:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Sub Load_RecordGrid_Layout()
        Try
            Dim XMLPath = Get_RecordGrid_Layout_Filename()
            If File.Exists(XMLPath) Then
                GridViewRecords.RestoreLayoutFromXml(XMLPath)
                GridViewRecords.GuessAutoFilterRowValuesFromFilter()
            End If

        Catch ex As Exception
            MsgBox("Error in Load_RecordGrid_Layout:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Private Function Get_RecordGrid_Layout_Filename()
        Dim EntityRegex As New RegularExpressions.Regex("\s+\(\d+\)")
        Dim Filename As String = "frmGlobalSearch_RecordGrid-UserLayout.xml"
        Return System.IO.Path.Combine(Application.UserAppDataPath(), Filename)
    End Function
    Private Function Get_DocGrid_Layout_Filename()
        Dim EntityRegex As New RegularExpressions.Regex("\s+\(\d+\)")
        Dim Filename As String = "frmGlobalSearch_DocGrid-UserLayout.xml"
        Return System.IO.Path.Combine(Application.UserAppDataPath(), Filename)
    End Function

    Private Sub frmSearchAllOVer_Load(sender As Object, e As EventArgs) Handles Me.Load
        Load_DocGrid_Layout()
        Load_RecordGrid_Layout()
    End Sub
End Class