Imports System.IO
'Imports System.Runtime.InteropServices
'Imports System.Text
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraPrinting

Public Class frmDocSearchResult
    '   <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 DT_RESULT As DataTable
    Private SelectedDocID As Int64
    Private SelectedFULL_FILEPATH As String
    Public Sub LoadDocSearch(reload As Boolean)
        Try
            Cursor = Cursors.WaitCursor

            If reload = False Then
                DT_RESULT = MYDB_ECM.GetDatatable(CURRENT_DOCSEARCH_SQL)
            End If

            DT_RESULT = DT_RESULT
            bsiInfo.Caption = $"{CURRENT_DOCSEARCH_CAPTION} ({DT_RESULT.Rows.Count} rows)"
            GridControlDocSearch.DataSource = DT_RESULT
            GridViewDoc_Search.OptionsView.ColumnAutoWidth = False
            GridViewDoc_Search.BestFitColumns()
            Load_DocGrid_Layout()
            Try
                GridViewDoc_Search.Columns.Item("FULL_FILENAME").Visible = False
            Catch ex As Exception

            End Try

        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in LoadDocSearch: " & ex.Message)
        End Try
        Cursor = Cursors.Default

    End Sub
    Private Sub GridViewDoc_Search_FocusedColumnChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs) Handles GridViewDoc_Search.FocusedColumnChanged
        If GridViewDoc_Search.RowCount > 0 Then
            GetDocID()
            Refresh_DocID()
        End If

    End Sub

    Private Sub GridViewDoc_Search_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs) Handles GridViewDoc_Search.FocusedRowChanged
        If GridViewDoc_Search.RowCount > 0 Then
            GetDocID()
            Refresh_DocID()
        End If
    End Sub
    Sub Refresh_DocID()
        If SelectedDocID <> 0 Then
            Dim msg = "Doc-ID: " & SelectedDocID.ToString
            bsiDocID.Caption = msg

        Else
            bsiDocID.Caption = "DocRow not selected"

        End If
    End Sub
    Sub GetDocID()
        Try
            Dim oDocID = GridViewDoc_Search.GetRowCellValue(GridViewDoc_Search.FocusedRowHandle, "DocID")
            SelectedFULL_FILEPATH = GridViewDoc_Search.GetRowCellValue(GridViewDoc_Search.FocusedRowHandle, "FULL_FILENAME")
            If Not IsNothing(oDocID) Then
                SelectedDocID = oDocID
                SelectedFULL_FILEPATH = GridViewDoc_Search.GetRowCellValue(GridViewDoc_Search.FocusedRowHandle, "FULL_FILENAME")
            End If

        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub

    Sub Open_File()
        Me.Cursor = Cursors.WaitCursor
        Dim allow_Open As Boolean = False
        GetDocID()
        Dim Result = ClassDOC_SEARCH.Get_File_Rights(SelectedDocID)
        If Not IsNothing(Result) Then
            Select Case Result.ToString
                Case "R"

                    allow_Open = True
                Case "RW"
                    allow_Open = True
                Case "RWA"
                    allow_Open = True
            End Select
        End If
        If allow_Open = True Then
            If IsNothing(SelectedDocID) Then
                MsgBox("Could not read File Parameters(5)!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            ClassHelper.File_open(SelectedFULL_FILEPATH, SelectedDocID)
            If CURRENT_OFFICE_FILE_CHANGED = True Then LoadDocSearch(True)

        Else
            ClassHelper.MSGBOX_Handler("ERROR", "", "File does not exist! Please contact your admin!")
        End If
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub docCM_Open_Click(sender As Object, e As EventArgs) Handles docCM_Open.Click
        Open_File()
    End Sub

    Private Sub OrdnerÖffnenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OrdnerÖffnenToolStripMenuItem.Click
        If IsNothing(SelectedFULL_FILEPATH) Then
            MsgBox("Could not read File Parameters(5)!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If

        ClassHelper.Open_Folder(SelectedFULL_FILEPATH, SelectedDocID)

    End Sub

    Private Sub docCM_Copy_Click(sender As Object, e As EventArgs) Handles docCM_Copy.Click
        If ClassWindreamDocGrid.SELECTED_DOC_PATH <> "" Then
            Try
                Dim selectedfile(0) As String
                selectedfile(0) = ClassWindreamDocGrid.SELECTED_DOC_PATH
                Dim dataobj As New DataObject
                dataobj.SetData(DataFormats.FileDrop, True, selectedfile)

                Clipboard.Clear()
                Clipboard.SetDataObject(dataobj, True)
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Copy file:", ex.Message)
            End Try
            Cursor = Cursors.Default
        End If
    End Sub

    Private Sub docCM_Showlinks_Click(sender As Object, e As EventArgs) Handles docCM_Showlinks.Click
        Try
            ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
            If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
                MsgBox("Could not read File Parameters (LinkRecord)!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If

            Dim frm As New frmDoc_Links
            frm.Show()
            frm.BringToFront()
        Catch ex As Exception
            MsgBox("Unexpected Error in Showing DocLinks: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub docCM_PropertiesFile_Click(sender As Object, e As EventArgs) Handles docCM_PropertiesFile.Click
        'Show_File_Properties()
    End Sub
    'Sub Show_File_Properties()
    '    If IsNothing(SelectedFULL_FILEPATH) Then
    '        MsgBox("Could not read File Parameters(4)!", MsgBoxStyle.Exclamation)
    '        Exit Sub
    '    End If
    '    If SelectedFULL_FILEPATH <> "" Then
    '        Cursor = Cursors.WaitCursor
    '        Dim sei As New SHELLEXECUTEINFO
    '        sei.cbSize = Marshal.SizeOf(sei)
    '        sei.lpVerb = "properties"
    '        sei.lpFile = SelectedFULL_FILEPATH
    '        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 properties:", ex.Message)
    '        End If
    '    End If
    '    Cursor = Cursors.Default

    'End Sub

    Private Sub frmDocSearchResult_Load(sender As Object, e As EventArgs) Handles Me.Load
        LoadDocSearch(False)
        Me.Text = CURRENT_DOCSEARCH_CAPTION
    End Sub
    Sub Save_DocGrid_Layout()
        Try
            Dim XMLPath = Get_DocGrid_Layout_Filename()
            GridViewDoc_Search.SaveLayoutToXml(XMLPath)
            ' Update_Status_Label(True, "Grid Layout Loaded")
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Sub Load_DocGrid_Layout()
        Try

            Dim XMLPath = Get_DocGrid_Layout_Filename()
            If File.Exists(XMLPath) Then
                GridViewDoc_Search.RestoreLayoutFromXml(XMLPath)
                GridViewDoc_Search.GuessAutoFilterRowValuesFromFilter()
            End If

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Private Function Get_DocGrid_Layout_Filename()
        Dim Filename As String = String.Format("GridViewDocSearchSW-{0}-UserLayout.xml", CURRENT_ENTITY_ID)
        LAYOUT_DOC_GRIDVIEW = System.IO.Path.Combine(Application.UserAppDataPath(), Filename)
        Return LAYOUT_DOC_GRIDVIEW
    End Function

    Private Sub frmDocSearchResult_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Save_DocGrid_Layout()
    End Sub

    Private Sub GridControlDocSearch_DoubleClick(sender As Object, e As EventArgs) Handles GridControlDocSearch.DoubleClick
        GetDocID()
        Refresh_DocID()
    End Sub

    Private Sub GridViewDoc_Search_ColumnFilterChanged(sender As Object, e As EventArgs) Handles GridViewDoc_Search.ColumnFilterChanged
        bsiInfo.Caption = $"{CURRENT_DOCSEARCH_CAPTION} ({GridViewDoc_Search.RowCount} rows [filtered])"

    End Sub

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs)
        LoadDocSearch(False)
    End Sub





    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        Dim XMLPath = Get_DocGrid_Layout_Filename()
        If File.Exists(XMLPath) Then
            File.Delete(XMLPath)
            LoadDocSearch(True)
        End If
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        Try
            Dim saveFileDialogDocSearchResult As New SaveFileDialog
            saveFileDialogDocSearchResult.Filter = "Excel File|*.xlsx"
            saveFileDialogDocSearchResult.Title = "Export to Excel:"
            saveFileDialogDocSearchResult.ShowDialog()
            If saveFileDialogDocSearchResult.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
                GridControlDocSearch.MainView.ExportToXlsx(saveFileDialogDocSearchResult.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(saveFileDialogDocSearchResult.FileName)
                End If
            End If

        Catch ex As Exception
            MsgBox("Unexpected Error in ExportExcel: " & ex.Message, MsgBoxStyle.Critical)
        End Try
        Cursor = Cursors.Default
    End Sub
End Class