Imports System.Windows.Forms
Imports System.IO
Imports Microsoft.Office.Interop
Imports System.Drawing

Public Class usrcntlPDFScanList
    Public Property _DATENSERVER_KATEGORIE As String = "DOKUMENTE"
    Public Property _DATENSERVER_ORDNER As String = ""
    Public Property _DATENSERVER_UOrdner1 As String = ""
    Public Property _DATENSERVER_UOrdner2 As String = ""
    Public Property _DATENSERVER_UOrdner3 As String = ""
    Public Property _OPEN_ORIGINAL As Boolean = False

    Private Property _TEXT_PDF As String = "SONSTIGE"
    Private Property _MULTI_FILES As Boolean = True

    Public Property _TYPE As String = "PDF"
    ' Public pdf_Path As String = ""
    Dim KdNr As Integer = -1

    'Dim DATENSERVER As New cDATENSERVER
    ' Public ScanID As Integer = -1
    Public COLL_ID As Integer = -1
    'Dim DatenserverIDCollection As New cDatenserverIDCollectionList
    Public DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER


    Public Event FileAdded(id As String, path As String, name As String)
    Public Event FileDeleted()

    Private draggedFilePath As String = ""

    Private Sub usrcntlPDFScan_Layout(sender As Object, e As LayoutEventArgs) Handles Me.Layout
        '  Me.txt.Text = _TEXT_PDF
        Me.MyListBox1.Dock = DockStyle.Fill
    End Sub

    Public Sub INIT_daId(da_id)
        DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER(da_id)
        initPdf()
    End Sub

    Public Sub INIT(KdNr)
        Me.KdNr = KdNr
        DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", _DATENSERVER_ORDNER, _DATENSERVER_UOrdner1, _DATENSERVER_UOrdner2, _DATENSERVER_UOrdner3, _TEXT_PDF, KdNr, _MULTI_FILES)
        initPdf()
    End Sub


    Public Sub INIT(KdNr, _DATENSERVER_UOrdner1)
        Me.KdNr = KdNr
        Me._DATENSERVER_UOrdner1 = _DATENSERVER_UOrdner1
        DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", _DATENSERVER_ORDNER, _DATENSERVER_UOrdner1, _DATENSERVER_UOrdner2, _DATENSERVER_UOrdner3, _TEXT_PDF, KdNr, _MULTI_FILES)
        initPdf()
    End Sub

    Public Sub INIT(KdNr, _DATENSERVER_UOrdner1, _DATENSERVER_UOrdner2)
        Me.KdNr = KdNr
        Me._DATENSERVER_UOrdner1 = _DATENSERVER_UOrdner1
        Me._DATENSERVER_UOrdner2 = _DATENSERVER_UOrdner2
        DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", _DATENSERVER_ORDNER, _DATENSERVER_UOrdner1, _DATENSERVER_UOrdner2, _DATENSERVER_UOrdner3, _TEXT_PDF, KdNr, _MULTI_FILES)
        initPdf()
    End Sub

    Public Sub INIT(KdNr, _DATENSERVER_UOrdner1, _DATENSERVER_UOrdner2, _DATENSERVER_UOrdner3)
        Me.KdNr = KdNr
        Me._DATENSERVER_UOrdner1 = _DATENSERVER_UOrdner1
        Me._DATENSERVER_UOrdner2 = _DATENSERVER_UOrdner2
        Me._DATENSERVER_UOrdner3 = _DATENSERVER_UOrdner3
        DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", _DATENSERVER_ORDNER, _DATENSERVER_UOrdner1, _DATENSERVER_UOrdner2, _DATENSERVER_UOrdner3, _TEXT_PDF, KdNr, _MULTI_FILES)
        initPdf()
    End Sub


    Private Sub usrcntlPDFScan_Load(sender As Object, e As EventArgs) Handles Me.Load
        ' Me.txt.Text = _TEXT_PDF
        Me.AllowDrop = True
        picAdd.ContextMenuStrip = cntxtMulti
        MyListBox1.ContextMenuStrip = cntxt
        ' Else
        '    If DatenserverIDCollection.Count > 0 Then
        'pdf_Path = DATENSERVER.getPathById(ScanID)

        picAdd.Left = Me.Width - picAdd.Width - 2
        picAdd.Top = Me.Height - picAdd.Height - 2
    End Sub

    Public Fill

    ' Sub addId(id)
    '     If id > 0 Then
    '         ScanID = id
    '        pdf_Path = DATENSERVER.getPathById(ScanID)
    '       initPdf()
    '    End If
    '  End Sub
    Public Function get_DA_ID() As Integer
        If DS IsNot Nothing AndAlso DS.hasITEMS Then
            If DS.da_id IsNot Nothing Then
                Return DS.da_id
            End If
        End If
        Return -1
    End Function
    Public Sub initPdf()
        MyListBox1.Items.Clear()

        KopierenZwischenablageToolStripMenuItem.Enabled = False
        AlsEmailSendenToolStripMenuItem.Enabled = False
        UmbenennenToolStripMenuItem.Enabled = False

        If DS.DATA_LIST.LIST.Count > 0 Then
            For Each i In DS.DATA_LIST.LIST
                MyListBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem(i.coll_bezeichnung, i.coll_id))
            Next
            KopierenZwischenablageToolStripMenuItem.Enabled = True
            AlsEmailSendenToolStripMenuItem.Enabled = True
            UmbenennenToolStripMenuItem.Enabled = True

            LöschenToolStripMenuItem.Enabled = VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Datenarchiv_DELETE", "SDL")
        End If

    End Sub





    '  Private Sub toolScannen_Click(sender As Object, e As EventArgs) Handles toolScannen.Click
    '      Process.Start(pdf_Path)

    ' End Sub


    Private Sub DateiScannenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem1.Click
        If KdNr < 0 Then Exit Sub
        Dim frmScan As New VERAG_PROG_ALLGEMEIN.frmScan("DirectScan")
        frmScan.DefaultFileName = Me._TEXT_PDF
        If frmScan.ShowDialog(Me) = DialogResult.OK Then
            If frmScan.ReturnValue IsNot Nothing Then
                Dim Filename = _TEXT_PDF
                If frmScan.fileName <> "" Then Filename = frmScan.fileName
                ' If _MULTI_FILES Then Filename &= Now.ToString("_ddMMyyyy_HHmmss")
                'Dim path = DATENSERVER.uploadDataToDATENSERVER_fromBytes(frmScan.ReturnValue, "DOKUMENTE", _DATENSERVER_ORDNER, KdNr, Filename, ".pdf")
                If DS.uploadDataToDATENSERVER_fromBytes(frmScan.ReturnValue, Filename, ".pdf") Then
                    If DS.DATA_LIST.LIST.Count > 0 Then
                        Dim l As VERAG_PROG_ALLGEMEIN.cDatenarchiv_Collection = DS.DATA_LIST.LIST(DS.DATA_LIST.LIST.Count - 1)
                        RaiseEvent FileAdded(l.coll_daId, l.coll_pfad, l.coll_bezeichnung)
                    End If
                End If


                ' Me.ScanID = DATENSERVER.LAST_ID
                ' Dim file As New FileInfo(frmScan.ReturnValue)
                'If file.Exists Then
                ' Me.pdf_Path = path
                'DS.DATA_LIST.ADD(Path, VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getTMPPath( Filename,"")


                'End If
            End If
        End If
        initPdf()
    End Sub

    Private Sub DateiHochladenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem2.Click
        If DS.uploadDataToDATENSERVERFileDialog_MULTI(, , , _TYPE) Then
            initPdf()
            RaiseEvent FileAdded(DS.da_id, DS.GET_TOP1_PATH, DS.da_name)
        End If
        'If DS.uploadDataToDATENSERVERFileDialog(, ".pdf", , "PDF") <> "" Then
        '    If DS.DATA_LIST.LIST.Count > 0 Then
        '        Dim l As VERAG_PROG_ALLGEMEIN.cDatenarchiv_Collection = DS.DATA_LIST.LIST(DS.DATA_LIST.LIST.Count - 1)
        '        RaiseEvent FileAdded(l.coll_id, l.coll_pfad, l.coll_bezeichnung)
        '    End If
        'End If

        'initPdf()

        ' Dim fd As New OpenFileDialog
        ' fd.Filter = "PDF|*.PDF"
        ' fd.DefaultExt = "pdf"
        ' If fd.ShowDialog() = DialogResult.OK Then
        'Dim Filename = _TEXT_PDF
        ' If _MULTI_FILES Then Filename &= Now.ToString("_ddMMyyyy_HHmmss")
        ' Dim path = DATENSERVER.uploadDataToDATENSERVER(fd.FileName, "DOKUMENTE", _DATENSERVER_ORDNER, KdNr, Filename, ".pdf")
        '  DatenserverIDCollection.ADD(DATENSERVER.LAST_ID, path, Filename)
        ' RaiseEvent FileAdded(DATENSERVER.LAST_ID, path, Filename)
        ' End If
    End Sub

    Private Sub LöschenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LöschenToolStripMenuItem.Click 'NUR WENN MULTI = FALSE
        Try
            If vbYes = MsgBox("Möchten Sie die '" & MyListBox1.SelectedItems.Count & "' selektierte(n) Datei(en) wirklich löschen? Die Daten gehen unwiederruflich verloren.", vbYesNoCancel, "Löschen") Then
                For Each SI In MyListBox1.SelectedItems
                    Dim DelItem As VERAG_PROG_ALLGEMEIN.MyListItem = DirectCast(SI, VERAG_PROG_ALLGEMEIN.MyListItem)
                    DS.DELETE_LIST_POS(DelItem.Value)
                Next
                If DS.DATA_LIST.LIST.Count = 0 Then
                    DS.DELETE_COMPLETE()
                End If
                initPdf()
                RaiseEvent FileDeleted()
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub picAdd_Click(sender As Object, e As EventArgs) Handles picAdd.Click
        cntxtMulti.Show(Windows.Forms.Cursor.Position)
    End Sub

    Private Sub MyListBox1_DoubleClick(sender As Object, e As EventArgs) Handles MyListBox1.DoubleClick
        Try
            If _OPEN_ORIGINAL Then
                Dim collId = DirectCast(MyListBox1.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value
                For Each i In DS.DATA_LIST.LIST
                    If i.coll_id = collId Then
                        Process.Start(i.coll_pfad)
                        Exit Sub
                    End If
                Next
            Else
                DS.OPEN(DirectCast(MyListBox1.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value,, True)
            End If


            '  VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.copyToTmp_KeepFilename(ii.coll_pfad, ii.coll_bezeichnung)

        Catch ex As Exception
            MsgBox("Fehler beim Öffnen!")
        End Try
    End Sub

    Private Sub MyListBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles MyListBox1.MouseClick
        If e.Button = Windows.Forms.MouseButtons.Right Then
            Dim i = MyListBox1.IndexFromPoint(e.X, e.Y)
            If i > 0 Then
                MyListBox1.SelectedIndex = i
                If MyListBox1.SelectedItems.Count > 0 Then cntxt.Show(Windows.Forms.Cursor.Position)
            Else
                cntxt.Hide()
            End If
        End If
    End Sub

    Private Sub UmbenennenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles UmbenennenToolStripMenuItem.Click
        Try
            If MyListBox1.SelectedItems.Count = 1 Then
                Dim item As MyListItem = DirectCast(MyListBox1.SelectedItems(0), MyListItem)
                Dim bez = InputBox("Bitte geben Sie eine neue Bezeichnung ein:", , item.Text)
                If bez <> "" Then
                    For Each i In DS.DATA_LIST.LIST
                        If i.coll_id = item.Value Then
                            i.coll_bezeichnung = bez
                            i.UPDATE()
                            initPdf()
                            Exit Sub
                        End If
                    Next
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Dim fired = False
    Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
        Try
            If keyData = (Keys.Control Or Keys.C) Then
                KopierenZwischenablageToolStripMenuItem_Click(KopierenZwischenablageToolStripMenuItem, New EventArgs)
            End If

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function

    Private Sub KopierenZwischenablageToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles KopierenZwischenablageToolStripMenuItem.Click
        Try
            VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.clearTMPPath("ClipBoard_TMP")
            Dim f(MyListBox1.SelectedItems.Count - 1) As String
            Dim cnt = 0
            If MyListBox1.SelectedItems.Count >= 1 Then
                For Each SI In MyListBox1.SelectedItems
                    Dim item As MyListItem = DirectCast(SI, MyListItem) 'DirectCast(MyListBox1.SelectedItems(0), MyListItem)
                    For Each ii In DS.DATA_LIST.LIST
                        If ii.coll_id = item.Value Then
                            'Dim f() As String = {ii.coll_pfad}
                            If ii.coll_pfad <> "" Then
                                f(cnt) = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.copyToTmp_KeepFilename(ii.coll_pfad, ii.coll_bezeichnung)
                                cnt += 1
                                'Exit For
                            End If
                        End If
                    Next
                Next
                'Zwischenablage
                Clipboard.Clear()
                Dim d As New DataObject(DataFormats.FileDrop, f)
                Clipboard.SetDataObject(d, True)
                Exit Sub
            End If
        Catch ex As Exception
            MsgBox("Fehler beim Laden der Daten!")
        End Try
    End Sub


    Private Sub AlsEmailSendenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AlsEmailSendenToolStripMenuItem.Click
        Try
            VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.clearTMPPath("ClipBoard_TMP")
            If MyListBox1.SelectedItems.Count >= 1 Then
                Try
                    Dim outl As New Outlook.Application
                    Dim Mail As Microsoft.Office.Interop.Outlook.MailItem
                    Mail = outl.CreateItem(0)

                    For Each SI In MyListBox1.SelectedItems
                        Dim item As MyListItem = DirectCast(SI, MyListItem) 'DirectCast(MyListBox1.SelectedItems(0), MyListItem)
                        For Each ii In DS.DATA_LIST.LIST
                            If ii.coll_id = item.Value Then
                                If ii.coll_pfad <> "" Then
                                    Mail.Attachments.Add(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.copyToTmp_KeepFilename(ii.coll_pfad, ii.coll_bezeichnung), Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue)
                                End If
                            End If
                        Next
                    Next

                    Mail.Display()
                Catch ex As Exception
                    MsgBox("Fehler beim Öffnen der Mail!")
                End Try
            End If
        Catch ex As Exception
            MsgBox("Fehler beim Öffnen der Mail!")
        End Try
    End Sub



    Private Sub Form1_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter ', txt.DragEnter, Me.DragEnter, picPDF.DragEnter
        e.Effect = DragDropEffects.All
    End Sub
    Private Sub txt_Click(sender As Object, e As DragEventArgs) Handles Me.DragDrop ', txt.DragDrop, Me.DragDrop, picPDF.DragDrop
        'If e.Data.GetDataPresent("FileDrop", True) = True Then
        '    Dim FileList As String() = CType(e.Data.GetData("FileDrop"), Object) 'Hier wird der Variable "Wert" das übergeben, was wir auf die Form gezogen haben. Bei einer Datei wäre es dann der Pfad der Datei.
        '    If FileList.Count > 0 Then
        '        If Not _MULTI_FILES And FileList.Count > 1 Then
        '            MsgBox("Es können nicht mehrere Dateien hochgeladen werden!")
        '            Exit Sub
        '        End If
        '        For Each W In FileList
        '            If W.ToUpper.EndsWith(".PDF") Then
        '                Try
        '                    Dim bezeichnung = System.IO.Path.GetFileName(W).ToString
        '                    DS.uploadDataToDATENSERVER(W, bezeichnung, ".pdf")
        '                    'Dim l As VERAG_PROG_ALLGEMEIN.cDatenarchiv_Collection = DS.DATA_LIST.LIST(DS.DATA_LIST.LIST.Count - 1)
        '                    'RaiseEvent FileAdded(l.coll_id, l.coll_pfad, l.coll_bezeichnung)
        '                    'If DS.DATA_LIST.LIST.Count > 0 Then
        '                    '    Dim l As VERAG_PROG_ALLGEMEIN.cDatenarchiv_Collection = DS.DATA_LIST.LIST(DS.DATA_LIST.LIST.Count - 1)
        '                    '    RaiseEvent FileAdded(l.coll_id, l.coll_pfad, l.coll_bezeichnung)
        '                    'End If
        '                Catch ex As Exception
        '                    MsgBox("FEHLER: UserControl möglicherweise nicht initialisiert!" & ex.Message & ex.StackTrace)
        '                End Try
        '            End If
        '        Next
        '        initPdf()
        '    End If
        'End If


        Try
            Dim added = False

            If DS IsNot Nothing Then

                If e.Data.GetDataPresent(DataFormats.FileDrop) Then
                    Dim files() As String = e.Data.GetData(DataFormats.FileDrop)

                    If files.Count > 1 Then
                        MsgBox("Nur eine Datei möglich!")
                    ElseIf files.Count > 0 Then
                        If files(0) <> "" Then
                            Dim fio As New System.IO.FileInfo(files(0))
                            If DS.uploadDataToDATENSERVER(files(0), fio.Name, ".pdf") Then
                                RaiseEvent FileAdded(DS.da_id, DS.GET_TOP1_PATH, DS.da_name)
                                MsgBox("Dokument wurde hochgeladen.")
                            End If

                        End If
                    End If

                ElseIf e.Data.GetDataPresent("FileGroupDescriptor") Then
                    Dim FilePath = VERAG_PROG_ALLGEMEIN.cProgramFunctions.EmAilAttach(e)
                    If FilePath <> "" Then
                        Dim fio As New System.IO.FileInfo(FilePath)
                        If DS.uploadDataToDATENSERVER(FilePath, fio.Name, ".pdf") Then
                            RaiseEvent FileAdded(DS.da_id, DS.GET_TOP1_PATH, DS.da_name)
                            MsgBox("Dokument wurde hochgeladen.")
                        End If
                    End If
                End If

                initPdf()

            End If


        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try


    End Sub

    Private Function GetFolderUnderCursor() As String
        Try
            Dim cursorPos As Point = Cursor.Position
            Dim shell As Object = CreateObject("Shell.Application")
            Dim folder As Object = shell.Namespace(0) ' Desktop level

            ' Get all open Explorer windows
            For Each window In shell.Windows()
                Dim explorerPath As String = window.Document.Folder.Self.Path
                If Not String.IsNullOrEmpty(explorerPath) Then
                    ' Check if the cursor is within the window bounds
                    Dim rect As Rectangle = New Rectangle(window.Left, window.Top, window.Width, window.Height)
                    If rect.Contains(cursorPos) Then
                        Return explorerPath ' Return detected folder path
                    End If
                End If
            Next
        Catch ex As Exception
            Return ""
        End Try
        Return ""
    End Function

    Private Sub cntxt_Opening(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles cntxt.Opening
        UmbenennenToolStripMenuItem.Visible = (MyListBox1.SelectedItems.Count = 1)
    End Sub

    Private Sub usrcntlPDFScanList_DragLeave(sender As Object, e As EventArgs) 'Handles MyBase.DragLeave


        If Not String.IsNullOrEmpty(draggedFilePath) Then
            Try
                ' Get the folder path where the cursor moved
                Dim cursorPath As String = GetFolderUnderCursor()

                If Not String.IsNullOrEmpty(cursorPath) AndAlso Directory.Exists(cursorPath) Then
                    ' Copy file to the detected folder
                    Dim destinationPath As String = Path.Combine(cursorPath, Path.GetFileName(draggedFilePath))
                    File.Copy(draggedFilePath, destinationPath, True)

                    MessageBox.Show("PDF saved to: " & destinationPath, "File Saved", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Else
                    MessageBox.Show("Could not determine the target folder.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                End If
            Catch ex As Exception
                MessageBox.Show("Error saving PDF: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try

        End If


    End Sub


End Class
