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.Data.Filtering
Imports DevExpress.Persistent.BaseImpl

Imports System.Linq
Imports System.Reflection
Imports DevExpress.ExpressApp.Utils

Public Class ContactsVC
    Inherits DevExpress.ExpressApp.ViewController

    Public Event InitWork(ByVal _Minimum As Long, ByVal _Step As Long, ByVal _Maximum As Long)
    Public Event DoWork()
    Public Event FinalWork()

    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()
        If View.Id = "Contact_EmailSendQueue_PopUp_HTMLMailTemplate_ListView" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.LinkUnlinkController).Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController).Active.SetItemValue("", False)
        End If
    End Sub
    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()
        If View.Id = "Contact_EmailSendQueue_PopUp_HTMLMailTemplate_ListView" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController).Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.LinkUnlinkController).Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController).Active.SetItemValue("", True)
        End If
    End Sub

    Public Sub New()
        MyBase.New()

        'This call is required by the Component Designer.
        InitializeComponent()
        RegisterActions(components)

    End Sub

    Private Sub aCreateActivityContacts_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aCreateActivityContacts.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _ListView As ListView = TryCast(View, ListView)
        Dim _PropertyCollectionSource As PropertyCollectionSource = TryCast(_ListView.CollectionSource, PropertyCollectionSource)
        Dim _Contacts As Contacts = TryCast(_PropertyCollectionSource.MasterObject, Contacts)
        Dim _CRM_Leads As CRM_Leads = _Contacts.CRM_Leads
        Dim _CRM_Leads_Activity As CRM_Leads_Activity = _onew.CreateObject(Of CRM_Leads_Activity)()

        Dim currentUser As User = _ocur.GetObjectByKey(Of User)(_ocur.GetKeyValue(SecuritySystem.CurrentUser))
        Frame.GetController(Of DevExpress.ExpressApp.Validation.PersistenceValidationController)().Active.SetItemValue("", False)

        If _CRM_Leads Is Nothing Then
            _CRM_Leads = _ocur.CreateObject(Of CRM_Leads)()
            _CRM_Leads.Contacts = _Contacts
            _CRM_Leads.FirstName = _Contacts.FirstName
            _CRM_Leads.LastName = _Contacts.LastName
            _CRM_Leads.HRPerson = _ocur.FindObject(Of HRPerson)(CriteriaOperator.Parse("User=?", currentUser))
            _CRM_Leads.CRM_FirstMeet = _ocur.FindObject(Of CRM_FirstMeet)(CriteriaOperator.Parse("DefaultforBusiness=True"))
            _CRM_Leads.LeadStatus = eLeadStatus.Qualified
        End If
        _Contacts.CRM_Leads = _CRM_Leads
        _ocur.CommitChanges()

        If _CRM_Leads IsNot Nothing Then
            _CRM_Leads_Activity.CRM_Leads = _onew.GetObject(_CRM_Leads)
            _CRM_Leads_Activity.HRPerson = _onew.GetObject(_CRM_Leads.HRPerson)
        End If

        Frame.GetController(Of DevExpress.ExpressApp.Validation.PersistenceValidationController)().Active.SetItemValue("", True)

        e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "CRM_Leads_Activity_DetailView", True, _CRM_Leads_Activity)
    End Sub
    Private Sub aContacts_ChangeGroup_CustomizePopupWindowParams(sender As Object, e As DevExpress.ExpressApp.Actions.CustomizePopupWindowParamsEventArgs) Handles aContacts_ChangeGroup.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _Contacts_ChangeGroup_PopUp As Contacts_ChangeGroup_PopUp = _onew.CreateObject(Of Contacts_ChangeGroup_PopUp)()
            e.View = Application.CreateDetailView(_onew, "Contacts_ChangeGroup_PopUp_DetailView", True, _Contacts_ChangeGroup_PopUp)

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\NuvolarExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aContacts_ChangeGroup_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.PopupWindowShowActionExecuteEventArgs) Handles aContacts_ChangeGroup.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = View.ObjectSpace
            Dim _Contacts_ChangeGroup_PopUp As Contacts_ChangeGroup_PopUp = TryCast(e.PopupWindow.View.SelectedObjects(0), Contacts_ChangeGroup_PopUp)

            RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)

            For Each _Contacts As Contacts In View.SelectedObjects
                RaiseEvent DoWork()
                If _Contacts_ChangeGroup_PopUp.ChangeIsOutlookSync Then
                    _Contacts.IsOutlookSync = _Contacts_ChangeGroup_PopUp.IsOutlookSync
                End If
                If _Contacts_ChangeGroup_PopUp.ChangeIsExchangeSync Then
                    _Contacts.IsExchangeSync = _Contacts_ChangeGroup_PopUp.IsExchangeSync
                End If
                If _Contacts_ChangeGroup_PopUp.ReOrderFirstNameLastName Then
                    Dim _FirstName As String = _Contacts.LastName
                    Dim _LastName As String = _Contacts.FirstName
                    _Contacts.FirstName = _FirstName
                    _Contacts.LastName = _LastName
                End If
                If _Contacts_ChangeGroup_PopUp.Change_FullNameOrder Then
                    _Contacts.FullNameOrder = _Contacts_ChangeGroup_PopUp.FullNameOrder
                End If
                If _Contacts_ChangeGroup_PopUp.Change_Title Then
                    _Contacts.Title = _Contacts_ChangeGroup_PopUp.Title
                End If
            Next
            _ocur.CommitChanges()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\NuvolarExceptions", "MsgBoxCheckItAgain")))
        Finally
            RaiseEvent FinalWork()
        End Try
    End Sub

    Private Sub aCreateEmailSendQueue_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aCreateEmailSendQueue.CustomizePopupWindowParams

        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _Contact_EmailSendQueue_PopUp As Contact_EmailSendQueue_PopUp = _onew.CreateObject(Of Contact_EmailSendQueue_PopUp)()
        e.View = Application.CreateDetailView(_onew, "Contact_EmailSendQueue_PopUp_DetailView", True, _Contact_EmailSendQueue_PopUp)

    End Sub

    Private Sub aCreateEmailSendQueue_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aCreateEmailSendQueue.Execute

        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _Contact_EmailSendQueue_PopUp As Contact_EmailSendQueue_PopUp = _onew.GetObject(TryCast(e.PopupWindow.View.SelectedObjects(0), Contact_EmailSendQueue_PopUp))
            Dim _ListPropertyEditor As Editors.ListPropertyEditor = TryCast(e.PopupWindow.View, DetailView).FindItem("HTMLMailTemplate")
            Dim _HTMLMailTemplate As HTMLMailTemplate = _ListPropertyEditor.ListView.SelectedObjects(0)
            If _HTMLMailTemplate Is Nothing Then Throw New Exception("*Nincs kiválasztva a sablon!")

            Dim _EMailSendQueueHeader As New EMailSendQueueHeader(_onew.Session)
            With _EMailSendQueueHeader
                .ShortName = _HTMLMailTemplate.ShortName
                .EmailSendQueueParameters = _onew.GetObject(Of EMailSendQueueParameters)(_Contact_EmailSendQueue_PopUp.EMailSendQueueParameters)
            End With


            Dim _ArrayList_Char As New ArrayList
            If _HTMLMailTemplate.HTMLBody Is Nothing Then Throw New Exception("*A HTML törzs üres!")
            Dim _StringBuilder As New StringBuilder
            Dim _TagBuilding As Boolean = False
            For Each _char As Char In _HTMLMailTemplate.HTMLBody
                Select Case _char
                    Case "{"c
                        _TagBuilding = True
                        _StringBuilder.Append(_char)
                    Case "}"c
                        _TagBuilding = False
                        _StringBuilder.Append(_char)
                        _ArrayList_Char.Add(_StringBuilder.ToString)
                        _StringBuilder.Clear()
                    Case Else
                        If _TagBuilding Then
                            _StringBuilder.Append(_char)
                        End If
                End Select
            Next
            _StringBuilder.Clear()

            For Each _Contacts As Contacts In View.SelectedObjects
                Dim _EMailSendQueueRows As New EMailSendQueueRows(_onew.Session)
                With _EMailSendQueueRows
                    .EMailSendQueueHeader = _EMailSendQueueHeader
                    .EMailTo = _Contacts.Email
                    .EMailFrom = TryCast(_onew.FindObject(Of WebParameters)(CriteriaOperator.Parse("1=1")), WebParameters).Email_SupportAdmin
                    _EMailSendQueueRows.HTMLBody = _HTMLMailTemplate.HTMLBody

                    For Each _PropertyInfo As PropertyInfo In _Contacts.GetType.GetProperties
                        If _ArrayList_Char.Contains("{" + _PropertyInfo.Name + "}") Then
                            If _PropertyInfo.GetValue(_Contacts, Nothing) IsNot Nothing Then
                                .HTMLBody = .HTMLBody.Replace("{" + _PropertyInfo.Name + "}", (_PropertyInfo.GetValue(_Contacts, Nothing)).ToString)
                            Else
                                .HTMLBody = .HTMLBody.Replace("{" + _PropertyInfo.Name + "}", " ")
                            End If

                        End If
                    Next
                    .Subject = _HTMLMailTemplate.ShortName

                    If _Contact_EmailSendQueue_PopUp.FileAttachments1 IsNot Nothing Then
                        Dim FileData As FileData = TryCast(_Contact_EmailSendQueue_PopUp.FileAttachments1, FileData)
                        Dim _FileLocation1 As String = String.Empty
                        _FileLocation1 = SaveOtherFile(FileData)
                        .FileAttachments1 = LoadOtherFile(_FileLocation1, New FileData(_onew.Session))
                    End If

                    If _Contact_EmailSendQueue_PopUp.FileAttachments2 IsNot Nothing Then
                        Dim FileData As FileData = TryCast(_Contact_EmailSendQueue_PopUp.FileAttachments2, FileData)
                        Dim _FileLocation2 As String = String.Empty
                        _FileLocation2 = SaveOtherFile(FileData)
                        .FileAttachments2 = LoadOtherFile(_FileLocation2, New FileData(_onew.Session))
                    End If
                    If _Contact_EmailSendQueue_PopUp.FileAttachments3 IsNot Nothing Then
                        Dim FileData As FileData = TryCast(_Contact_EmailSendQueue_PopUp.FileAttachments3, FileData)
                        Dim _FileLocation3 As String = String.Empty
                        _FileLocation3 = SaveOtherFile(FileData)
                        .FileAttachments3 = LoadOtherFile(_FileLocation3, New FileData(_onew.Session))
                    End If

                End With
            Next
            _onew.CommitChanges()

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\NuvolarExceptions", "MsgBoxCheckItAgain")))
        End Try

    End Sub
    Private Function SaveOtherFile(ByRef _FileData As FileData) As String
        Dim _FileName As String = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetTempPath, _FileData.FileName)
        Dim _StreamFile As System.IO.Stream = New System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)
        _FileData.SaveToStream(_StreamFile)
        _StreamFile.Close()

        Return _FileName

    End Function
    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

    'Dim _HTMLMailTemplate_CollectionSource As New CollectionSource(_onew, GetType(HTMLMailTemplate))
    '_HTMLMailTemplate_CollectionSource.BeginUpdateCriteria()
    '_HTMLMailTemplate_CollectionSource.Criteria.Clear()
    '_HTMLMailTemplate_CollectionSource.Criteria.Add("HTMLMailTemplateState", CriteriaOperator.Parse("HTMLMailTemplateState=1"))
    '_HTMLMailTemplate_CollectionSource.EndUpdateCriteria()
    'e.View = Application.CreateListView("HTMLMailTemplate_ListView", _HTMLMailTemplate_CollectionSource, True)


    'Private Function SaveOtherFile(ByRef _IntoFile As String, _fileData As FileData) As FileData
    '    Dim _FileName As String = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetTempPath, _IntoFile)
    '    Dim _StreamFile As System.IO.Stream = New System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)
    '    _fileData.SaveToStream(_StreamFile)
    '    _StreamFile.Close()

    '    Return _fileData
    'End Function

    Private Sub aContactEmailToClipboard_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aContactEmailToClipboard.Execute
        Dim _ClipboardText As String = ""
        If Windows.Forms.Clipboard.ContainsText(System.Windows.Forms.TextDataFormat.Text) Then
            _ClipboardText = Windows.Forms.Clipboard.GetText(Windows.Forms.TextDataFormat.Text)
        End If
        For Each _Contacts As Contacts In View.SelectedObjects
            If _ClipboardText = "" Then
                _ClipboardText += _Contacts.Email
            Else
                _ClipboardText += ";" + _Contacts.Email
            End If
        Next
        Windows.Forms.Clipboard.SetText(_ClipboardText, Windows.Forms.TextDataFormat.UnicodeText)
    End Sub

    Private Sub aClearClipboard_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aClearClipboard.Execute
        Windows.Forms.Clipboard.Clear()
    End Sub
End Class
