Imports DevExpress.Utils
Imports System.Text
Imports System.IO
Imports DevExpress.XtraGrid.Views.Grid
Imports System.Runtime.InteropServices
Imports DevExpress.XtraPrinting
Imports DevExpress.Data.Filtering.Helpers.SubExprHelper.CriteriaTokens
Imports DevExpress.XtraSplashScreen
Imports System.Threading

Public Class frmGlobalSearch
    Inherits DevExpress.XtraBars.Ribbon.RibbonForm
    <DllImport("Shell32", CharSet:=CharSet.Auto, SetLastError:=True)>
    Public Shared Function ShellExecuteEx(ByRef lpExecInfo As SHELLEXECUTEINFO) As Boolean
    End Function
    Public Structure SHELLEXECUTEINFO
        Public cbSize As Integer
        Public fMask As Integer
        Public hwnd As IntPtr
        <MarshalAs(UnmanagedType.LPTStr)> Public lpVerb As String
        <MarshalAs(UnmanagedType.LPTStr)> Public lpFile As String
        <MarshalAs(UnmanagedType.LPTStr)> Public lpParameters As String
        <MarshalAs(UnmanagedType.LPTStr)> Public lpDirectory As String
        Dim nShow As Integer
        Dim hInstApp As IntPtr
        Dim lpIDList As IntPtr
        <MarshalAs(UnmanagedType.LPTStr)> Public lpClass As String
        Public hkeyClass As IntPtr
        Public dwHotKey As Integer
        Public hIcon As IntPtr
        Public hProcess As IntPtr
    End Structure
    Private Const SEE_MASK_INVOKEIDLIST = &HC
    Private Const SEE_MASK_NOCLOSEPROCESS = &H40
    Private Const SEE_MASK_FLAG_NO_UI = &H400
    Public Const SW_SHOW As Short = 5
    Private _Helper As ClassHelper
    Dim sel_Records, sel_FT As String
    Private SelectedGrid As DevExpress.XtraGrid.GridControl

    Sub Refresh_Search()
        If txtSearch.Text = "" Then
            Exit Sub
        End If
        Dim oHandle = SplashScreenManager.ShowOverlayForm(Me)
        Try
            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



        Catch ex As Exception

        Finally
            SplashScreenManager.CloseOverlayForm(oHandle)
        End Try




    End Sub
    Sub PREPARE_FT_SQL()
        Dim oFTSearchtext = txtSearch.Text
        If oFTSearchtext.Contains(" ") Then
            oFTSearchtext = oFTSearchtext.Replace(" ", "%")
        End If
        Dim sqlft = SQL_FULLTEXT
        sqlft = sqlft.Replace("@FULLTEXT", oFTSearchtext)
        'Dim selDoc = String.Format("SELECT T.[DocID],T.[FULL_FILENAME],T.[Filename],T.[DISPLAY_NAME],T.[Doctype],T.[Creation_DateTime] As CreatedWhen,T.[Change_DateTime] as ChangedWhen,T.[IN_WORK] as [InWork?] " &
        '            "FROM VWPMO_DOC_SEARCH T INNER JOIN ( " & vbNewLine &
        '            "{0}) Y ON  T.DocID = Y.dwDocID " & vbNewLine &
        '            "INNER JOIN VWPMO_WD_OBJECT_RIGHTS TRIGHT ON T.DocID = TRIGHT.dwObjectID WHERE TRIGHT.dwUserOrGroupID = {1}", sqlft, USERID_FK_INT_ECM)
        sel_FT = sqlft

    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 = MYDB_ECM.GetDatatable(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 = MYDB_ECM.GetDatatable(sel_FT)
        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
                GridViewFiles.OptionsView.ColumnAutoWidth = False
                GridViewFiles.BestFitColumns()
            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 ExportExcelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExportExcelToolStripMenuItem.Click
        Export_Excel()
    End Sub
    Sub Export_Excel()
        If IsNothing(SelectedGrid) Then
            MsgBox("Please choose a grid!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        Dim saveFileDialog1 As New SaveFileDialog
        saveFileDialog1.Filter = "Excel File|*.xlsx"
        saveFileDialog1.Title = "Export to Excel:"
        saveFileDialog1.ShowDialog()
        If saveFileDialog1.FileName <> "" Then
            Cursor = Cursors.WaitCursor
            Dim oOptions As XlsxExportOptionsEx = New XlsxExportOptionsEx
            oOptions.ShowGridLines = True
            oOptions.AllowSortingAndFiltering = DevExpress.Utils.DefaultBoolean.True
            oOptions.ExportType = DevExpress.Export.ExportType.DataAware
            oOptions.ExportMode = XlsxExportMode.SingleFile
            oOptions.AllowFixedColumnHeaderPanel = DevExpress.Utils.DefaultBoolean.True
            SelectedGrid.MainView.ExportToXlsx(saveFileDialog1.FileName, oOptions)
            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 GridControlFiles_DoubleClick(sender As Object, e As EventArgs) Handles GridControlFiles.DoubleClick
        File_open()
    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
        _Helper = New ClassHelper
        Load_DocGrid_Layout()
        Load_RecordGrid_Layout()
    End Sub
    Sub Show_File_Properties()
        Try
            For Each row In GridViewFiles.GetSelectedRows
                Dim SELECTED_DOC_PATH = _Helper.FORMAT_WM_PATH(GridViewFiles.GetRowCellValue(row, "FULL_FILENAME"))
                Dim SELECTED_DOC_ID = GridViewFiles.GetRowCellValue(row, "DocID")

                Cursor = Cursors.WaitCursor
                Dim sei As New SHELLEXECUTEINFO
                sei.cbSize = Marshal.SizeOf(sei)
                sei.lpVerb = "properties"
                sei.lpFile = SELECTED_DOC_PATH
                sei.nShow = SW_SHOW
                sei.fMask = SEE_MASK_INVOKEIDLIST
                If Not ShellExecuteEx(sei) Then
                    Dim ex As New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
                    ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Open file propertys:", ex.Message)
                End If
            Next

        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Sub Open_folder()
        Try
            For Each row In GridViewFiles.GetSelectedRows
                Dim SELECTED_DOC_PATH = _Helper.FORMAT_WM_PATH(GridViewFiles.GetRowCellValue(row, "FULL_FILENAME"))
                Dim SELECTED_DOC_ID = GridViewFiles.GetRowCellValue(row, "DocID")
                ClassHelper.Open_Folder(SELECTED_DOC_PATH, SELECTED_DOC_ID)
            Next


        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try



    End Sub

    Private Sub GridControlRecords_DoubleClick(sender As Object, e As EventArgs) Handles GridControlRecords.DoubleClick

    End Sub

    Private Sub DateiÖffnenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DateiÖffnenToolStripMenuItem.Click
        File_open()
    End Sub

    Private Sub OrdnerÖffnenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OrdnerÖffnenToolStripMenuItem.Click
        Open_folder()
    End Sub

    Private Sub EigenschaftenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EigenschaftenToolStripMenuItem.Click
        Show_File_Properties()
    End Sub

    Private Sub VerknüpfungenAnzeigenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VerknüpfungenAnzeigenToolStripMenuItem.Click
        Try
            For Each row In GridViewFiles.GetSelectedRows
                Dim SELECTED_DOC_ID = GridViewFiles.GetRowCellValue(row, "DocID")
                If IsNothing(SELECTED_DOC_ID) Then
                    MsgBox("Could not Get a selected DocID!", MsgBoxStyle.Exclamation)
                    Exit Sub
                End If
                CURRENT_DOC_ID = SELECTED_DOC_ID
                Dim frm As New frmDoc_Links
                frm.Show()
                frm.BringToFront()
            Next
        Catch ex As Exception
            MsgBox("Unexpected Error in Showing DocLinks: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub GridControlRecords_Click(sender As Object, e As EventArgs) Handles GridControlRecords.Click
        SelectedGrid = sender
    End Sub

    Private Sub GridControlFiles_Click(sender As Object, e As EventArgs) Handles GridControlFiles.Click
        SelectedGrid = sender
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        Export_Excel()
    End Sub

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        Show_Detail_Record()
    End Sub

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

    Sub File_open()
        Me.Cursor = Cursors.WaitCursor

        For Each row In GridViewFiles.GetSelectedRows
            Dim SELECTED_DOC_PATH = _Helper.FORMAT_WM_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
End Class