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.ExpressApp.Editors
Imports DevExpress.XtraRichEdit.API.Native
Imports DevExpress.XtraRichEdit
Imports DevExpress.Persistent.BaseImpl
Imports DevExpress.ExpressApp.SystemModule
Imports DevExpress.Data.Filtering
Imports DevExpress.ExpressApp.Utils
Imports DevExpress.ExpressApp.TreeListEditors.Win
Imports DevExpress.XtraTreeList
Imports DevExpress.ExpressApp.Win.Controls
Imports DevExpress.XtraSpreadsheet
Imports DevExpress.XtraSpreadsheet.Services

Public Class BusinessDirectory_VC
    Inherits Nuvolar.Module.BusinessDirectory_VC

    Private _RichEditControl As RichEditControl
    Private _SpreadsheetControl As SpreadsheetControl
    Private _ISpreadsheetCommandFactoryService As ISpreadsheetCommandFactoryService

    Public Sub New()
        MyBase.New()
        InitializeComponent()
        RegisterActions(components)
    End Sub
    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()
        If View.Id = "OpenRTFDocument_PopUp_DetailView" Then
            Frame.GetController(Of ModificationsController).SaveAction.Active.SetItemValue("", False)
            Frame.GetController(Of ModificationsController).SaveAndCloseAction.Active.SetItemValue("", False)
            Frame.GetController(Of ModificationsController).SaveAndNewAction.Active.SetItemValue("", False)

            Dim _DetailView As DetailView = TryCast(View, DetailView)
            Dim _RichEditContolViewItem As ViewItem = _DetailView.FindItem("RTFText")
            If _RichEditContolViewItem IsNot Nothing Then
                AddHandler _RichEditContolViewItem.ControlCreated, AddressOf RichEditContolViewItem_ControlCreated
            End If
        End If
        If View.Id = "OpenSpreadDocument_Popup_DetailView" Then
            Frame.GetController(Of ModificationsController).SaveAction.Active.SetItemValue("", False)
            Frame.GetController(Of ModificationsController).SaveAndCloseAction.Active.SetItemValue("", False)
            Frame.GetController(Of ModificationsController).SaveAndNewAction.Active.SetItemValue("", False)

            Frame.GetController(Of CloneObject.CloneObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of NewObjectViewController).Active.SetItemValue("", False)

            Dim _DetailView As DetailView = TryCast(View, DetailView)
            Dim _SpreadXML_ViewItem As ViewItem = _DetailView.FindItem("SpreadXML")
            If _SpreadXML_ViewItem IsNot Nothing Then
                AddHandler _SpreadXML_ViewItem.ControlCreated, AddressOf _SpreadXML_ViewItem_ControlCreated
            End If
        End If
        If View.Id = "BusinessDirectory_ListView" Then
            AddHandler View.ControlsCreated, AddressOf BusinessDirectory_ListView_ControlsCreated
        End If

    End Sub

    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()
        If View.Id = "OpenRTFDocument_PopUp_DetailView" Then
            Frame.GetController(Of ModificationsController).SaveAction.Active.SetItemValue("", True)
            Frame.GetController(Of ModificationsController).SaveAndCloseAction.Active.SetItemValue("", True)
            Frame.GetController(Of ModificationsController).SaveAndNewAction.Active.SetItemValue("", True)
        End If
        If View.Id = "BusinessDirectory_ListView" Then
            RemoveHandler View.ControlsCreated, AddressOf BusinessDirectory_ListView_ControlsCreated
        End If
    End Sub
    Private Sub aBusinessDirectory_OpenRTFDocument_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aBusinessDirectory_OpenRTFDocument.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _BusinessDirectory As BusinessDirectory = TryCast(View.SelectedObjects(0), BusinessDirectory)
        Dim _FileType As String = GetFileType(_BusinessDirectory.FileData)
        If _FileType = ".rtf" Or _FileType = ".RTF" Or _FileType = ".doc" Or _FileType = ".DOC" Or _FileType = ".docx" Or _FileType = ".DOCX" Then
            Dim _OpenRTFDocument_PopUp As New OpenRTFDocument_PopUp(_onew.Session)
            Dim _RichEditControl_New As New RichEditControl
            _BusinessDirectory.Reload()
            _RichEditControl_New.LoadDocument(GetFile(_BusinessDirectory.FileData))
            _OpenRTFDocument_PopUp.RTFText = _RichEditControl_New.RtfText
            _OpenRTFDocument_PopUp.BusinessDirectory = _onew.GetObject(_BusinessDirectory)

            e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "OpenRTFDocument_PopUp_DetailView", True, _OpenRTFDocument_PopUp)
        End If
    End Sub
    Private Sub aBusinessDirectory_OpenSpreadDocument_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aBusinessDirectory_OpenSpreadDocument.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _BusinessDirectory As BusinessDirectory = TryCast(View.SelectedObjects(0), BusinessDirectory)
        Dim _FileType As String = GetFileType(_BusinessDirectory.FileData)
        If UCase(_FileType) = ".XLS" Or UCase(_FileType) = ".XLSX" Then
            Dim _OpenSpreadDocument_PopUp As New OpenSpreadDocument_Popup(_onew.Session)
            _OpenSpreadDocument_PopUp.BusinessDirectory = _onew.GetObject(_BusinessDirectory)
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "OpenSpreadDocument_Popup_DetailView", True, _OpenSpreadDocument_PopUp)
        End If
    End Sub
    Private Sub aOpenRTFDocument_InsertTable_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aOpenRTFDocument_InsertTable.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _User As User = _onew.GetObjectByKey(Of User)(_onew.GetKeyValue(SecuritySystem.CurrentUser))
            Dim _RTFCopy As RTFCopy = _onew.FindObject(Of RTFCopy)(CriteriaOperator.Parse("UserCreated=?", _User))
            If _RTFCopy Is Nothing Then Throw New Exception("*Nincs táblázat elhelyezve a vágólapon!")
            Dim _ContractTemplate As ContractTemplate = TryCast(View.SelectedObjects(0), ContractTemplate)

            Dim _DocPos As DocumentPosition = _RichEditControl.Document.CaretPosition

            _RichEditControl.Document.InsertHtmlText(_DocPos, _RTFCopy.RTFString)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\NuvolarExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aOpenRTFDocument_SaveBusinessDiretory_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aOpenRTFDocument_SaveBusinessDiretory.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _OpenRTFDocument_PopUp As OpenRTFDocument_PopUp = TryCast(View.SelectedObjects(0), OpenRTFDocument_PopUp)
        Dim _BusinessDirectory As BusinessDirectory = _ocur.GetObject(_OpenRTFDocument_PopUp.BusinessDirectory)

        _RichEditControl.SaveDocument(IO.Path.GetTempPath + _BusinessDirectory.FileData.FileName.Remove(_BusinessDirectory.FileData.FileName.Length - 4, 4) + ".rtf", DocumentFormat.Rtf)

        _BusinessDirectory.FileData = LoadOtherFile(IO.Path.GetTempPath + _BusinessDirectory.FileData.FileName.Remove(_BusinessDirectory.FileData.FileName.Length - 4, 4) + ".rtf", New FileData(_ocur.Session))

        _BusinessDirectory.FileCreated = GetFileCreatedDate(IO.Path.GetTempPath + _BusinessDirectory.FileData.FileName.Remove(_BusinessDirectory.FileData.FileName.Length - 4, 4) + ".rtf")
        _BusinessDirectory.FileCreated = GetFileModifiedDate(IO.Path.GetTempPath + _BusinessDirectory.FileData.FileName.Remove(_BusinessDirectory.FileData.FileName.Length - 4, 4) + ".rtf")

        If IO.File.Exists(IO.Path.GetTempPath + _BusinessDirectory.FileData.FileName.Remove(_BusinessDirectory.FileData.FileName.Length - 4, 4) + ".rtf") Then _
            IO.File.Delete(IO.Path.GetTempPath + _BusinessDirectory.FileData.FileName.Remove(_BusinessDirectory.FileData.FileName.Length - 4, 4) + ".rtf")

        _ocur.CommitChanges()
        _BusinessDirectory.Reload()
        View.Close()
    End Sub
    Private Sub aOpenRTFDocument_SaveToCRM_Lead_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aOpenRTFDocument_SaveToCRM_Lead.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _OpenRTFDocument_PopUp As OpenRTFDocument_PopUp = TryCast(View.SelectedObjects(0), OpenRTFDocument_PopUp)
            If _OpenRTFDocument_PopUp Is Nothing Then Throw New Exception("*Váratlan hiba történt a folyamat megszakadt!")
            Dim _RichEditControlNew As New RichEditControl
            _RichEditControlNew.RtfText = _OpenRTFDocument_PopUp.RTFText

            Dim _RTFDocumentsCreatorHeader As New RTFDocumentsCreatorHeader(_onew.Session)
            Dim _Fields As DevExpress.XtraRichEdit.API.Native.FieldCollection = _RichEditControlNew.Document.Fields
            Dim _Document As DevExpress.XtraRichEdit.API.Native.Document = _RichEditControlNew.Document
            For Each _ActTagString As DevExpress.XtraRichEdit.API.Native.Field In _Fields
                Dim _RTFDocumentsCreatorRows As New RTFDocumentsCreatorRows(_onew.Session)
                With _RTFDocumentsCreatorRows
                    .RTFDocumentsCreatorHeader = _RTFDocumentsCreatorHeader
                    .InfoString = _Document.GetText(_ActTagString.CodeRange)
                    _RTFDocumentsCreatorHeader.RTFDocumentsCreatorRows.Add(_RTFDocumentsCreatorRows)
                End With
            Next
            _RTFDocumentsCreatorHeader.FileName = _OpenRTFDocument_PopUp.BusinessDirectory.FileData.FileName

            e.View = Application.CreateDetailView(_onew, "RTFDocumentsCreatorHeader_DetailView", False, _RTFDocumentsCreatorHeader)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "Hiba!")
        End Try
    End Sub
    Private Sub aOpenRTFDocument_SaveToCRM_Lead_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aOpenRTFDocument_SaveToCRM_Lead.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _OpenRTFDocument_PopUp As OpenRTFDocument_PopUp = TryCast(View.SelectedObjects(0), OpenRTFDocument_PopUp)
            If _OpenRTFDocument_PopUp Is Nothing Then Throw New Exception("*Váratlan hiba történt a folyamat megszakadt!")
            Dim _RichEditControlNew As New RichEditControl
            _RichEditControlNew.RtfText = _OpenRTFDocument_PopUp.RTFText
            Dim _RTFDocumentsCreatorHeader As RTFDocumentsCreatorHeader = TryCast(e.PopupWindow.View.SelectedObjects(0), RTFDocumentsCreatorHeader)

            Dim _FieldIndex As Int16 = 0
            Dim _Fields As DevExpress.XtraRichEdit.API.Native.FieldCollection = _RichEditControlNew.Document.Fields

            _RichEditControlNew.BeginUpdate()

            Dim _Document As DevExpress.XtraRichEdit.API.Native.Document = _RichEditControlNew.Document

            _Document.BeginUpdate()

            For Each _RTFDocumentsCreatorRows As RTFDocumentsCreatorRows In _RTFDocumentsCreatorHeader.RTFDocumentsCreatorRows
                Dim field As DevExpress.XtraRichEdit.API.Native.Field = _Fields(_FieldIndex)
                field.ShowCodes = True
                Dim _FieldCode As String = _Document.GetText(field.CodeRange)
                Dim _FieldResult As String = _RTFDocumentsCreatorRows.ValueString
                Dim _FieldPosition As DocumentPosition = field.Range.Start
                _Document.Delete(field.Range)
                _Document.InsertText(_FieldPosition, _FieldResult)
            Next
            _Document.EndUpdate()
            _RichEditControlNew.EndUpdate()

            Dim _FilePath As String = System.IO.Path.GetTempPath
            Dim _FileName As String = ""
            Select Case _RTFDocumentsCreatorHeader.RTFExportFileType
                Case eRTFExportFileType.ePDF
                    _FileName = _RTFDocumentsCreatorHeader.FileName + ".pdf"
                    _RichEditControlNew.ExportToPdf(_FilePath + _FileName)
                Case eRTFExportFileType.eRTF
                    _FileName = _RTFDocumentsCreatorHeader.FileName + ".rtf"
                    _RichEditControlNew.SaveDocument(_FilePath + _FileName, DocumentFormat.Rtf)
                Case eRTFExportFileType.eWord
                    _FileName = _RTFDocumentsCreatorHeader.FileName + ".doc"
                    _RichEditControlNew.SaveDocument(_FilePath + _FileName, DocumentFormat.Doc)
                Case eRTFExportFileType.eWordXDoc
                    _FileName = _RTFDocumentsCreatorHeader.FileName + ".docx"
                    _RichEditControlNew.SaveDocument(_FilePath + _FileName, DocumentFormat.WordML)
            End Select

            If System.IO.File.Exists(_FilePath + _FileName) Then
                Dim _CRM_LeadsDocumentation As New CRM_LeadsDocumentation(_ocur.Session)
                With _CRM_LeadsDocumentation
                    .CRM_Leads = _ocur.GetObject(_OpenRTFDocument_PopUp.CRM_Opportunities.CRM_Leads)
                    .File = LoadOtherFile(_FilePath + _FileName, New DevExpress.Persistent.BaseImpl.FileData(_ocur.Session))
                    .FileCreated = GetFileCreatedDate(_FilePath + _FileName)
                    .FileModified = GetFileModifiedDate(_FilePath + _FileName)
                    .ShortName = .File.FileName
                    .Status = eProductsDocumentationStatus.ePublic
                End With

                System.IO.File.Delete(_FilePath + _FileName)
            End If

            _ocur.CommitChanges()
            View.Close()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "Hiba!")
        End Try
    End Sub
    Private Sub aOpenRTFDocument_InsertDocVariable_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aOpenRTFDocument_InsertDocVariable.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _RTFDocumanetsHandler_DocVariable_PopUp As New RTFDocumanetsHandler_DocVariable_PopUp(_onew.Session)

            e.View = Application.CreateDetailView(_onew, "RTFDocumanetsHandler_DocVariable_PopUp_DetailView", False, _RTFDocumanetsHandler_DocVariable_PopUp)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "Hiba!")
        End Try
    End Sub
    Private Sub aOpenRTFDocument_InsertDocVariable_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aOpenRTFDocument_InsertDocVariable.Execute
        Try
            Dim _RTFDocumanetsHandler_DocVariable_PopUp As RTFDocumanetsHandler_DocVariable_PopUp = TryCast(e.PopupWindow.View.SelectedObjects(0), RTFDocumanetsHandler_DocVariable_PopUp)
            _RichEditControl.Document.Fields.Add(_RichEditControl.Document.CaretPosition, "DOCVARIABLE " + _RTFDocumanetsHandler_DocVariable_PopUp.DocVariableString)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "Hiba!")
        End Try
    End Sub
    Private Sub BusinessDirectory_ListView_ControlsCreated(sender As Object, e As EventArgs)
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _TreeListEditor As TreeListEditor = CType((CType(View, DevExpress.ExpressApp.ListView)).Editor, TreeListEditor)
        Dim _TreeList As TreeList = _TreeListEditor.TreeList

        AddHandler _TreeList.FilterNode, AddressOf _TreeList_FilterNode
    End Sub
    Private Sub _TreeList_FilterNode(sender As Object, e As FilterNodeEventArgs)
        e.Handled = True
        If View Is Nothing Then Exit Sub
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _ObjectTreeListNode As ObjectTreeListNode = TryCast(e.Node, ObjectTreeListNode)
        Dim _BusinessDirectory As BusinessDirectory = TryCast(_ObjectTreeListNode.Object, BusinessDirectory)
        If _BusinessDirectory IsNot Nothing Then
            Dim _BusinessDirectory_Roles As BusinessDirectory_Roles = _ocur.FindObject(Of BusinessDirectory_Roles)(CriteriaOperator.Parse("BusinessDirectory=?", _BusinessDirectory))
            If _BusinessDirectory_Roles IsNot Nothing Then
                If SecuritySystemHelper.IsUserInRoleCurrentUser(_BusinessDirectory_Roles.Role.Name) Then
                    _ObjectTreeListNode.Visible = False
                End If
            End If
        End If
    End Sub
#Region "Other Functions and Subs"
    Private Function GetFileType(_FileData As FileData) As String
        Dim _FileExt As String = ""
        Dim _FilePath As String = System.IO.Path.Combine(System.IO.Path.GetTempPath(), _FileData.FileName)
        Dim _Stream As System.IO.Stream = New System.IO.FileStream(_FilePath, System.IO.FileMode.Create)
        _FileData.SaveToStream(_Stream)
        _Stream.Close()

        _FileExt = System.IO.Path.GetExtension(_FilePath)

        If IO.File.Exists(_FilePath) Then IO.File.Delete(_FilePath)

        Return _FileExt
    End Function
    Private Function GetFile(_DocumentFile As DevExpress.Persistent.BaseImpl.FileData) As String
        Dim _FilePath As String = System.IO.Path.Combine(System.IO.Path.GetTempPath(), _DocumentFile.FileName)
        Dim _Stream As System.IO.Stream = New System.IO.FileStream(_FilePath, System.IO.FileMode.Create)
        _DocumentFile.SaveToStream(_Stream)
        _Stream.Close()

        Return _FilePath
    End Function
    Private Sub RichEditContolViewItem_ControlCreated(sender As Object, e As EventArgs)
        Dim _ItemControl As Object = TryCast(sender, ViewItem).Control
        Dim _RichEditUserControl As RichEditUserControl = TryCast(_ItemControl, RichEditUserControl)
        _RichEditControl = TryCast(_ItemControl, RichEditUserControl).RichEditControl
    End Sub
    Private Sub _SpreadXML_ViewItem_ControlCreated(sender As Object, e As EventArgs)
        Dim _OpenSpreadDocument_PopUp As OpenSpreadDocument_Popup = TryCast(View.SelectedObjects(0), OpenSpreadDocument_Popup)
        Dim _ItemControl As Object = TryCast(sender, ViewItem).Control
        Dim _SpreadUserControl As SpreadUserControl = TryCast(_ItemControl, SpreadUserControl)

        _SpreadsheetControl = TryCast(_ItemControl, SpreadUserControl).SpreadsheetControl1

        _ISpreadsheetCommandFactoryService = _SpreadsheetControl.GetService(Of ISpreadsheetCommandFactoryService)()
        _SpreadsheetControl.ReplaceService(Of ISpreadsheetCommandFactoryService)(New CustomCommandFactoryServise(_ISpreadsheetCommandFactoryService, _SpreadsheetControl, View))

        '// IDE KELL !!! Itt már van SPREAD !!

        If _OpenSpreadDocument_PopUp IsNot Nothing Then
            If _OpenSpreadDocument_PopUp.BusinessDirectory IsNot Nothing Then
                If _OpenSpreadDocument_PopUp.BusinessDirectory.FileData IsNot Nothing Then
                    Dim _FilePath As String = System.IO.Path.Combine(System.IO.Path.GetTempPath(), _OpenSpreadDocument_PopUp.BusinessDirectory.FileData.FileName)
                    Dim _Stream As System.IO.Stream = New System.IO.FileStream(_FilePath, System.IO.FileMode.Create)
                    _OpenSpreadDocument_PopUp.BusinessDirectory.FileData.SaveToStream(_Stream)
                    _Stream.Close()


                    Dim _StreamFile = New System.IO.FileStream(_FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
                    Dim _StreamReader As New System.IO.StreamReader(_StreamFile)
                    Dim workbook As DevExpress.Spreadsheet.IWorkbook = _SpreadsheetControl.Document
                    _StreamFile.Seek(0, System.IO.SeekOrigin.Begin)
                    workbook.LoadDocument(_StreamFile, DevExpress.Spreadsheet.DocumentFormat.OpenXml)
                    _StreamFile.Close()
                End If
            End If
        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
#End Region

End Class
