Imports System
Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text

Imports DevExpress.ExpressApp
Imports DevExpress.ExpressApp.Actions
Imports DevExpress.Persistent.Base
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.XtraGrid.Views.Grid.ViewInfo

Imports Microsoft.VisualBasic
Imports System.Drawing
Imports System.Collections
Imports System.Windows.Forms
Imports System.Data
Imports DevExpress.ExpressApp.Win.Editors
Imports DevExpress.Persistent.BaseImpl
Imports DevExpress.ExpressApp.Win
Imports Microsoft.Office.Interop
Imports System.IO
Imports DevExpress.XtraTreeList
Imports DevExpress.ExpressApp.Win.Controls
Imports DevExpress.ExpressApp.TreeListEditors.Win
Imports DevExpress.XtraTreeList.Nodes
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Imports System.Collections.Specialized
Imports System.Threading

Public Class DragAndDropBusinessDirectory_VC
    Inherits DevExpress.ExpressApp.ViewController

    Private _TreeListEditor As TreeListEditor
    Private _TreeList As TreeList
    Private _Selection As New ArrayList
    Private _EnabledSelection = True
    Private _CanEmailDrop As Boolean = True
    Dim _WaitFormClass As New WaitFormClass

    Public Sub New()
        MyBase.New()
        InitializeComponent()
        RegisterActions(components)
    End Sub
    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()
        If View.Id Like "*BusinessDirectory_ListView*" Then
            AddHandler View.ControlsCreated, AddressOf View_ControlsCreated
        End If
    End Sub

    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()
        If View.Id = "BusinessDirectory_ListView" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).DeleteAction.Active.SetItemValue("", True)
        End If
    End Sub
    Private Sub View_ControlsCreated(sender As Object, e As EventArgs)
        _TreeListEditor = CType((CType(View, DevExpress.ExpressApp.ListView)).Editor, TreeListEditor)
        _TreeList = _TreeListEditor.TreeList
        _TreeList.OptionsDragAndDrop.DragNodesMode = DragNodesMode.Multiple
        _TreeList.OptionsDragAndDrop.ExpandNodeOnDrag = True

        AddHandler _TreeList.DragOver, AddressOf _TreeList_DragOver
        AddHandler _TreeList.DragDrop, AddressOf _TreeList_DragDrop
        AddHandler _TreeList.DragLeave, AddressOf _TreeList_DragLeave


        AddHandler View.SelectionChanged, AddressOf BusinessDirectory_ListView_SelectionChanged
    End Sub
#Region "Drag and Drop"

    Private Sub _TreeList_DragOver(sender As Object, e As DragEventArgs)
        'Dim dragNode As TreeListNode = TryCast(e.Data.GetData(GetType(TreeListNode)), TreeListNode)
        e.Effect = DragDropEffects.All


        'e.Effect = GetDragDropEffect(TryCast(sender, TreeList), dragNode, New Point(e.X, e.Y))
    End Sub
    Private Sub _TreeList_DragLeave(sender As Object, e As EventArgs)
        'Fileok Clipboard droplistba
        Dim _Paths As New StringCollection

        For Each _BusinessDirectory As BusinessDirectory In View.SelectedObjects
            If _BusinessDirectory.FileData IsNot Nothing Then
                Dim _FileName As String = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetTempPath, _BusinessDirectory.FileData.FileName)
                Dim _StreamFile As System.IO.Stream = New System.IO.FileStream(_FileName, System.IO.FileMode.Create)

                _BusinessDirectory.FileData.SaveToStream(_StreamFile)
                _StreamFile.Close()
                _Paths.Add(_FileName)

            End If
        Next
        If _Paths.Count > 0 Then
            Dim data As New DataObject()
            data.SetFileDropList(_Paths)
            _TreeList.DoDragDrop(data, DragDropEffects.Copy)
        End If

    End Sub
    Private Sub _TreeList_DragDrop(sender As Object, e As DragEventArgs)
        Dim _TargetNode As TreeListNode = Nothing
        Dim _Point As Point
        Dim _BusinessDirectoryDrop As Boolean = False
        Dim _FileDrop As Boolean = False
        Dim _EmailDrop As Boolean = False
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)

        Dim _TL As TreeList = TryCast(sender, TreeList)
        If _TL IsNot Nothing Then
            _Point = _TL.PointToClient(New Point(e.X, e.Y))
            _TargetNode = _TL.CalcHitInfo(_Point).Node

            If e.Data.GetDataPresent(DataFormats.FileDrop) Then
                _FileDrop = True
            ElseIf e.Data.GetDataPresent("FileGroupDescriptor") Then
                _EmailDrop = True
            ElseIf TryCast(DirectCast(_TargetNode, DevExpress.ExpressApp.Win.Controls.ObjectTreeListNode).Object, BusinessDirectory) IsNot Nothing Then
                _BusinessDirectoryDrop = True
            End If
        End If

        If _TargetNode Is Nothing Then Exit Sub

        If _BusinessDirectoryDrop Then
            Dim _TargetBusinessDirectory As BusinessDirectory = TryCast(DirectCast(_TargetNode, DevExpress.ExpressApp.Win.Controls.ObjectTreeListNode).Object, BusinessDirectory)
            If TryCast(_Selection(0), BusinessDirectory).Oid <> _TargetBusinessDirectory.Oid Then
                If _TargetBusinessDirectory.IsFolder Then
                    If _TargetBusinessDirectory IsNot Nothing Then
                        _EnabledSelection = False
                        For Each _BusinessDirectory As BusinessDirectory In _Selection
                            _BusinessDirectory.BusinessDirectory_Parent = _TargetBusinessDirectory
                        Next
                        _ocur.CommitChanges()
                        _EnabledSelection = True
                    End If
                Else
                    MsgBox("Fájl nem használható könyvtárként!", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Figyelem!")
                End If
            Else
                MsgBox("Nem helyezhető át az elem saját magába!", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Figyelem!")
            End If
        End If

        If _FileDrop Then
            Dim _FileIn As Object = e.Data.GetData(DataFormats.FileDrop)
            If _FileIn IsNot Nothing Then
                _Selection.Clear()
                Try
                    _WaitFormClass.Initwork(0, 1, TryCast(_FileIn, String()).Length)
                    For Each _ActFile As String In _FileIn
                        _WaitFormClass.DoWork()

                        If System.IO.File.Exists(_ActFile) Then
                            Dim _BusinessDirectory As New BusinessDirectory(_ocur.Session)
                            With _BusinessDirectory
                                .IsFolder = False
                                .ShortName = IO.Path.GetFileName(IO.Path.GetFileNameWithoutExtension(_ActFile))
                                .FileData = LoadOtherFile(_ActFile, New FileData(_ocur.Session))
                                .BusinessDirectory_Parent = TryCast(DirectCast(_TargetNode, DevExpress.ExpressApp.Win.Controls.ObjectTreeListNode).Object, BusinessDirectory)
                                .FileCreated = GetFileCreatedDate(_ActFile)
                                .FileModified = GetFileModifiedDate(_ActFile)
                            End With
                        End If
                    Next
                    _ocur.CommitChanges()
                Catch ex As Exception
                Finally
                    _WaitFormClass.FinalWork()
                End Try
            End If
        End If

        If _EmailDrop Then
            Dim _OL As Microsoft.Office.Interop.Outlook.Application = New Microsoft.Office.Interop.Outlook.Application
            Dim _Explorer As Microsoft.Office.Interop.Outlook.Explorer = _OL.ActiveExplorer
            Dim _TargetBusinessDirectory As BusinessDirectory = TryCast(DirectCast(_TargetNode, DevExpress.ExpressApp.Win.Controls.ObjectTreeListNode).Object, BusinessDirectory)
            If _TargetBusinessDirectory.IsFolder Then
                If _CanEmailDrop Then
                    If _Explorer.Selection.Count > 0 Then
                        _CanEmailDrop = False

                        Dim _MemoryStream As MemoryStream = TryCast(e.Data.GetData("FileGroupDescriptor"), MemoryStream)
                        Dim _TMPFileName As String = Path.GetTempPath + Path.GetRandomFileName

                        Dim _FileStream As FileStream = File.OpenWrite(_TMPFileName)
                        _MemoryStream.WriteTo(_FileStream)
                        _FileStream.Flush()
                        _FileStream.Close()

                        Dim _TxtLine As String = ""
                        If File.Exists(_TMPFileName) Then

                            Dim _StreamReader As New StreamReader(_TMPFileName)
                            Do While _StreamReader.Peek <> -1
                                _TxtLine += _StreamReader.ReadLine
                            Loop
                        End If

                        If _TxtLine.Contains(".msg") Then
                            Try
                                _WaitFormClass.Initwork(0, 1, _Explorer.Selection.Count)
                                For ik = 1 To _Explorer.Selection.Count
                                    _WaitFormClass.DoWork()
                                    Dim _FileIn As Object = _Explorer.Selection(ik)
                                    Dim _MailItem As Microsoft.Office.Interop.Outlook.MailItem = TryCast(_FileIn, Microsoft.Office.Interop.Outlook.MailItem)
                                    Dim _MeetingItem As Microsoft.Office.Interop.Outlook.MeetingItem = TryCast(_FileIn, Microsoft.Office.Interop.Outlook.MeetingItem)

                                    If _MailItem Is Nothing And _MeetingItem Is Nothing Then Throw New Exception("*Csak e-mail, értekezlet és találkozó típusú Outlook elemet lehet beilleszteni!")

                                    If _MailItem IsNot Nothing Then
                                        Try
                                            Dim _FileName As String = ""
                                            Dim _Subject As String = ""
                                            If _MailItem.Subject IsNot Nothing Then
                                                _Subject = _MailItem.Subject.Replace(":", "")
                                                _Subject = _Subject.Replace("/", "-")
                                            Else
                                                _Subject = "Nincs tárgy"
                                            End If

                                            If Not IsValidFileName(_Subject) Then Throw New Exception("*Illegális karakterek a tárgy mezőben!")

                                            _FileName = String.Format("{0}{1}.msg", System.IO.Path.GetTempPath, _Subject)
                                            _MailItem.SaveAs(_FileName, Microsoft.Office.Interop.Outlook.OlSaveAsType.olMSG)
                                            If System.IO.File.Exists(_FileName) Then
                                                Dim _BusinessDirectory As New BusinessDirectory(_ocur.Session)
                                                With _BusinessDirectory
                                                    .FileData = LoadOtherFile(_FileName, New FileData(_ocur.Session))
                                                    .FileData.FileName = IO.Path.GetFileName(_FileName)
                                                    .FileCreated = _MailItem.ReceivedTime 'Küldés dátuma kell?
                                                    .FileModified = GetFileModifiedDate(_FileName)
                                                    .ShortName = IO.Path.GetFileName(_FileName)
                                                    .BusinessDirectory_Parent = TryCast(DirectCast(_TargetNode, DevExpress.ExpressApp.Win.Controls.ObjectTreeListNode).Object, BusinessDirectory)
                                                    .IsFolder = False
                                                    .EMail_Sender = _MailItem.Sender.Name
                                                    .Email_Copy = _MailItem.CC
                                                End With
                                                System.IO.File.Delete(_FileName)
                                            End If

                                        Catch ex As Exception
                                            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "Hiba!")
                                        End Try
                                    ElseIf _MeetingItem IsNot Nothing Then
                                        Try
                                            Dim _FileName As String = ""
                                            Dim _Subject As String = ""
                                            If _MeetingItem.Subject IsNot Nothing Then
                                                _Subject = _MeetingItem.Subject.Replace(":", "")
                                                _Subject = _Subject.Replace("/", "-")
                                                _Subject = _Subject.Replace("|", "_")
                                            Else
                                                _Subject = "Nincs tárgy"
                                            End If

                                            If Not IsValidFileName(_Subject) Then Throw New Exception("*Illegális karakterek a tárgy mezőben!")

                                            _FileName = String.Format("{0}{1}.msg", System.IO.Path.GetTempPath, _Subject)
                                            _MeetingItem.SaveAs(_FileName, Microsoft.Office.Interop.Outlook.OlSaveAsType.olMSG)
                                            If System.IO.File.Exists(_FileName) Then
                                                Dim _BusinessDirectory As New BusinessDirectory(_ocur.Session)
                                                With _BusinessDirectory
                                                    .FileData = LoadOtherFile(_FileName, New FileData(_ocur.Session))
                                                    .FileData.FileName = IO.Path.GetFileName(_FileName)
                                                    .FileCreated = _MeetingItem.ReceivedTime 'Küldés dátuma kell?
                                                    .FileModified = GetFileModifiedDate(_FileName)
                                                    .ShortName = IO.Path.GetFileName(_FileName)
                                                    .BusinessDirectory_Parent = TryCast(DirectCast(_TargetNode, DevExpress.ExpressApp.Win.Controls.ObjectTreeListNode).Object, BusinessDirectory)
                                                    .IsFolder = False
                                                    .EMail_Sender = _MeetingItem.SenderName   '.Sender.Name
                                                End With
                                                System.IO.File.Delete(_FileName)
                                            End If

                                        Catch ex As Exception
                                            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "Hiba!")
                                        Finally
                                            _WaitFormClass.FinalWork()
                                        End Try
                                    End If
                                Next
                                _ocur.CommitChanges()
                            Catch ex As Exception
                            Finally
                                Marshal.ReleaseComObject(_Explorer)
                                Marshal.ReleaseComObject(_Explorer)
                                _Explorer = Nothing
                                Marshal.ReleaseComObject(_OL)
                                _OL = Nothing
                                _WaitFormClass.FinalWork()
                            End Try
                        Else
                            _WaitFormClass.Initwork(0, 1, 1)
                            _WaitFormClass.DoWork()
                            Dim _FileNameFromStream As New StringBuilder("")
                            _FileNameFromStream.Append(Path.GetTempPath)


                            Dim fileGroupDescriptor(512) As Byte
                            _MemoryStream.Read(fileGroupDescriptor, 0, 512)

                            Dim i As Integer = 76
                            While fileGroupDescriptor(i) <> 0
                                _FileNameFromStream.Append(Convert.ToChar(fileGroupDescriptor(i)))
                                i += 1
                            End While

                            Dim _FileIn As Object = _Explorer.Selection(1)
                            Dim _MailItem As Microsoft.Office.Interop.Outlook.MailItem = TryCast(_FileIn, Microsoft.Office.Interop.Outlook.MailItem)

                            For Each _Attachment As Microsoft.Office.Interop.Outlook.Attachment In _MailItem.Attachments
                                If _Attachment.FileName = Path.GetFileName(_FileNameFromStream.ToString) Then
                                    _Attachment.SaveAsFile(Path.GetTempPath + _Attachment.FileName)

                                    If System.IO.File.Exists(Path.GetTempPath + _Attachment.FileName) Then
                                        Dim _BusinessDirectory As New BusinessDirectory(_ocur.Session)
                                        With _BusinessDirectory
                                            .FileData = LoadOtherFile(Path.GetTempPath + _Attachment.FileName, New FileData(_ocur.Session))
                                            .FileData.FileName = IO.Path.GetFileName(Path.GetTempPath + _Attachment.FileName)
                                            .FileCreated = GetFileCreatedDate(Path.GetTempPath + _Attachment.FileName)
                                            .FileModified = GetFileModifiedDate(Path.GetTempPath + _Attachment.FileName)
                                            .ShortName = IO.Path.GetFileName(Path.GetTempPath + _Attachment.FileName)
                                            .BusinessDirectory_Parent = TryCast(DirectCast(_TargetNode, DevExpress.ExpressApp.Win.Controls.ObjectTreeListNode).Object, BusinessDirectory)
                                            .IsFolder = False
                                            .EMail_Sender = _MailItem.Sender.Name
                                            .Email_Copy = _MailItem.CC
                                        End With

                                        System.IO.File.Delete(Path.GetTempPath + _Attachment.FileName)
                                    End If
                                End If
                            Next

                            _ocur.CommitChanges()

                            Marshal.ReleaseComObject(_Explorer)
                            Marshal.ReleaseComObject(_Explorer)
                            _Explorer = Nothing
                            Marshal.ReleaseComObject(_OL)
                            _OL = Nothing

                            _WaitFormClass.FinalWork()
                        End If
                    End If
                End If
                _CanEmailDrop = True
            Else
                MsgBox("Fájl nem használható könyvtárként!", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Figyelem!")
            End If
        End If
        e.Effect = DragDropEffects.None
    End Sub

#End Region
    Private Function GetDragDropEffect(ByVal tl As TreeList, ByVal dragNode As TreeListNode, _Point As Point) As DragDropEffects
        Dim _TargetNode As TreeListNode
        Dim _PointNew As Point = tl.PointToClient(_Point)
        _TargetNode = tl.CalcHitInfo(_PointNew).Node

        Return DragDropEffects.Move
    End Function
    Private Sub BusinessDirectory_ListView_SelectionChanged(sender As Object, e As EventArgs)
        If _EnabledSelection Then
            _Selection.Clear()
            _Selection.AddRange(View.SelectedObjects)
        End If
    End Sub
    Private Function LoadOtherFile(ByVal _ActFile As String, _FileData As FileData) As FileData
        Dim _StreamFile = New System.IO.FileStream(_ActFile, System.IO.FileMode.Open, System.IO.FileAccess.Read)
        Dim _StreamReader As New System.IO.StreamReader(_StreamFile)
        _StreamFile.Seek(0, System.IO.SeekOrigin.Begin)

        _FileData.LoadFromStream(_ActFile, _StreamFile)
        _FileData.FileName = System.IO.Path.GetFileName(_ActFile)
        _StreamReader.Close()
        _StreamFile.Close()

        Return _FileData

    End Function
    Private Function GetFileCreatedDate(_ActFile As String) As Date
        Return System.IO.File.GetCreationTime(_ActFile)
    End Function
    Private Function GetFileModifiedDate(_ActFile As String) As Date
        Return System.IO.File.GetLastAccessTime(_ActFile)
    End Function
    Public Function IsValidFileName(ByVal fn As String) As Boolean
        Try
            Dim fi As New IO.FileInfo(fn)
        Catch ex As Exception
            Return False
        End Try
        Return True
    End Function





End Class
