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 Microsoft.Office.Interop.Outlook
Imports Microsoft.Office.Interop
Imports DevExpress.Xpo
Imports System.IO
Imports DevExpress.Data.Filtering
Imports DevExpress.ExpressApp.Utils

Public Class ContactsVC
    Inherits Nuvolar.Module.ContactsVC

    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 "Contacts_*" Then
            AddHandler MyBase.DoWork, AddressOf _WaitFormClass.DoWork
            AddHandler MyBase.InitWork, AddressOf _WaitFormClass.InitWork
            AddHandler MyBase.FinalWork, AddressOf _WaitFormClass.Finalwork
        End If

    End Sub
    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()
        If View.Id Like "Contacts_*" Then
            RemoveHandler MyBase.DoWork, AddressOf _WaitFormClass.DoWork
            RemoveHandler MyBase.InitWork, AddressOf _WaitFormClass.InitWork
            RemoveHandler MyBase.FinalWork, AddressOf _WaitFormClass.Finalwork
        End If
    End Sub
    Private Sub aContacts_SysncToOutlook_CustomizePopupWindowParams(sender As Object, e As DevExpress.ExpressApp.Actions.CustomizePopupWindowParamsEventArgs) Handles aContacts_SysncToOutlook.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _onew_Delete As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _Contacts_OutlookFolderContact_Collection As New XPCollection(Of Contacts_OutlookFolderContact)(_onew_Delete.Session)
            If _Contacts_OutlookFolderContact_Collection.Count > 0 Then
                _onew_Delete.Delete(_Contacts_OutlookFolderContact_Collection)
            End If
            _onew_Delete.CommitChanges()

            Dim _Contacts_SysncOutlook As Contacts_SysncOutlook = _onew.CreateObject(Of Contacts_SysncOutlook)()
            e.View = Application.CreateDetailView(_onew, "Contacts_SysncOutlook_DetailView", True, _Contacts_SysncOutlook)
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\NuvolarExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aContacts_SysncToOutlook_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.PopupWindowShowActionExecuteEventArgs) Handles aContacts_SysncToOutlook.Execute
        Try
            Frame.GetController(Of DevExpress.ExpressApp.Validation.PersistenceValidationController)().Active.SetItemValue("", False)
            Dim _ocur As Xpo.XPObjectSpace = View.ObjectSpace
            Dim _NeedCommitChanges As Boolean = False
            Dim _Contacts_SysncOutlook As Contacts_SysncOutlook = TryCast(e.PopupWindow.View.SelectedObjects(0), Contacts_SysncOutlook)
            Dim _OutlookApp As New Outlook.Application()
            Dim _OutlookNameSpace As Outlook.NameSpace = _OutlookApp.GetNamespace("MAPI")
            _OutlookNameSpace.Logon(, , False, True)
            _WaitFormClass.InitWork(0, 1, View.SelectedObjects.Count)
            Select Case _Contacts_SysncOutlook.SyscType
                Case eSyscType.eFirstSync
                    Dim _ContactFolder As Outlook.MAPIFolder = _OutlookNameSpace.GetFolderFromID(_Contacts_SysncOutlook.Contacts_OutlookFolderContact.EntryID)
                    For Each _Contacts As Contacts In View.SelectedObjects
                        _WaitFormClass.DoWork
                        If _Contacts.IsOutlookSync Then
                            Dim _FileName As String = Path.GetTempPath + _Contacts.Oid.ToString + ".jpg"
                            Dim _ContactItem As Outlook.ContactItem = _OutlookApp.CreateItem(OlItemType.olContactItem)
                            With (_ContactItem)
                                .FirstName = _Contacts.FirstName
                                .LastName = _Contacts.LastName
                                .Email1Address = _Contacts.Email
                                .Birthday = _Contacts.Birthday
                                .JobTitle = _Contacts.Position
                                .BusinessTelephoneNumber = _Contacts.BusinessTelephoneNumber
                                .BusinessFaxNumber = _Contacts.BusinessFaxNumber
                                .HomeFaxNumber = _Contacts.HomeFaxNumber
                                .MobileTelephoneNumber = _Contacts.MobileTelephoneNumber

                                If _Contacts.Photo IsNot Nothing Then
                                    '_Contacts.Photo.Save(_FileName)
                                    '.AddPicture(_FileName)
                                End If

                                If _Contacts.Address1 IsNot Nothing Then
                                    .BusinessAddress = _Contacts.Address1.FullAddress
                                    .BusinessAddressCity = _Contacts.Address1.City
                                    .BusinessAddressCountry = _Contacts.Address1.Country.Name
                                    .BusinessAddressPostalCode = _Contacts.Address1.ZipPostal
                                    .BusinessAddressState = _Contacts.Address1.StateProvince
                                    .BusinessAddressStreet = _Contacts.Address1.Street
                                End If

                                If _Contacts.Customers IsNot Nothing Then
                                    .Companies = _Contacts.Customers.FullName
                                    .CompanyName = _Contacts.Customers.Name
                                End If
                            End With

                            _ContactItem.User1 = _Contacts.Oid.ToString
                            _ContactItem.Save()
                            _ContactItem.Move(_ContactFolder)

                            If File.Exists(_FileName) Then File.Delete(_FileName)

                            _Contacts.ContactItemFolderEntryID_Outlook = _ContactFolder.EntryID
                        End If
                    Next
                    _NeedCommitChanges = True
                Case eSyscType.eNormalSysnc
                    Select Case _Contacts_SysncOutlook.OverWriteDataType
                        Case eOverWriteDataType.OverWriteOutlookData
                            For Each _Contacts As Contacts In View.SelectedObjects
                                _WaitFormClass.DoWork
                                Dim _FileName As String = Path.GetTempPath + _Contacts.Oid.ToString + ".jpg"
                                Dim _ContactFolder As Outlook.MAPIFolder = _OutlookNameSpace.GetFolderFromID(_Contacts.ContactItemFolderEntryID_Outlook)
                                Dim _ContactItem_Collection As Outlook.Items = _ContactFolder.Items
                                Dim _Filter As String = "[User1] = '" + _Contacts.Oid.ToString + "'"
                                Dim _ContactItem As Outlook.ContactItem = _ContactItem_Collection.Find(_Filter)
                                If _ContactItem IsNot Nothing Then
                                    _ContactItem.FirstName = _Contacts.FirstName
                                    _ContactItem.LastName = _Contacts.LastName
                                    _ContactItem.Email1Address = _Contacts.Email
                                    _ContactItem.Birthday = _Contacts.Birthday
                                    _ContactItem.JobTitle = _Contacts.Position
                                    _ContactItem.BusinessTelephoneNumber = _Contacts.BusinessTelephoneNumber
                                    _ContactItem.BusinessFaxNumber = _Contacts.BusinessFaxNumber
                                    _ContactItem.HomeFaxNumber = _Contacts.HomeFaxNumber
                                    _ContactItem.MobileTelephoneNumber = _Contacts.MobileTelephoneNumber

                                    If _Contacts.Photo IsNot Nothing Then
                                        '_Contacts.Photo.Save(_FileName)
                                        '_ContactItem.AddPicture(_FileName)
                                    End If

                                    If _Contacts.Address1 IsNot Nothing Then
                                        _ContactItem.BusinessAddress = _Contacts.Address1.FullAddress
                                        _ContactItem.BusinessAddressCity = _Contacts.Address1.City
                                        _ContactItem.BusinessAddressCountry = _Contacts.Address1.Country.Name
                                        _ContactItem.BusinessAddressPostalCode = _Contacts.Address1.ZipPostal
                                        _ContactItem.BusinessAddressState = _Contacts.Address1.StateProvince
                                        _ContactItem.BusinessAddressStreet = _Contacts.Address1.Street
                                    End If

                                    If _Contacts.Customers IsNot Nothing Then
                                        _ContactItem.Companies = _Contacts.Customers.FullName
                                        _ContactItem.CompanyName = _Contacts.Customers.Name
                                    End If
                                    If File.Exists(_FileName) Then File.Delete(_FileName)
                                End If
                                _ContactItem.Save()
                            Next
                        Case eOverWriteDataType.OverWriteNuvolarData
                            For Each _Contacts As Contacts In View.SelectedObjects
                                _WaitFormClass.DoWork
                                Dim _ContactFolder As Outlook.MAPIFolder = _OutlookNameSpace.GetFolderFromID(_Contacts.ContactItemFolderEntryID_Outlook)
                                Dim _ContactItem_Collection As Outlook.Items = _ContactFolder.Items
                                Dim _Filter As String = "[User1] = '" + _Contacts.Oid.ToString + "'"
                                Dim _ContactItem As Outlook.ContactItem = _ContactItem_Collection.Find(_Filter)
                                If _ContactItem IsNot Nothing Then
                                    Dim _FileName As String = Path.GetTempPath + _Contacts.Oid.ToString + ".jpg"

                                    _Contacts.FirstName = _ContactItem.FirstName
                                    _Contacts.LastName = _ContactItem.LastName
                                    _Contacts.Email = _ContactItem.Email1Address
                                    _Contacts.Birthday = _ContactItem.Birthday
                                    _Contacts.Position = _ContactItem.JobTitle
                                    _Contacts.BusinessTelephoneNumber = _ContactItem.BusinessTelephoneNumber
                                    _Contacts.BusinessFaxNumber = _ContactItem.BusinessFaxNumber
                                    _Contacts.HomeFaxNumber = _ContactItem.HomeFaxNumber
                                    _Contacts.MobileTelephoneNumber = _ContactItem.MobileTelephoneNumber

                                    Dim _Address As New DevExpress.Persistent.BaseImpl.Address(_ocur.Session)
                                    _Address.City = _ContactItem.BusinessAddressCity
                                    Dim _Country As New DevExpress.Persistent.BaseImpl.Country(_ocur.Session)
                                    _Country.Name = _ContactItem.BusinessAddressCountry
                                    _Address.Country = _Country
                                    _Address.ZipPostal = _ContactItem.BusinessAddressPostalCode
                                    _Address.StateProvince = _ContactItem.BusinessAddressState
                                    _Address.Street = _ContactItem.BusinessAddressStreet

                                    _Contacts.Address1 = _Address

                                    If Not String.IsNullOrEmpty(_ContactItem.Companies) Then
                                        Dim _Customers As Customers = _ocur.FindObject(Of Customers)(CriteriaOperator.Parse("FullName=?", _ContactItem.Companies))
                                        If _Customers IsNot Nothing Then
                                            _Contacts.Customers = _ocur.GetObject(_Customers)
                                        End If
                                    End If
                                End If
                            Next
                            _NeedCommitChanges = True
                    End Select
            End Select
            If _NeedCommitChanges Then _ocur.CommitChanges()
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\NuvolarExceptions", "MsgBoxCheckItAgain")))
        Finally
            _Waitformclass.FinalWork
            Frame.GetController(Of DevExpress.ExpressApp.Validation.PersistenceValidationController)().Active.SetItemValue("", True)
        End Try
    End Sub
    Private Sub aContacts_SysncFromOutlook_CustomizePopupWindowParams(sender As Object, e As DevExpress.ExpressApp.Actions.CustomizePopupWindowParamsEventArgs) Handles aContacts_SysncFromOutlook.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _onew_Delete As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _Contacts_OutlookFolderContact_Collection As New XPCollection(Of Contacts_OutlookFolderContact)(_onew_Delete.Session)
            If _Contacts_OutlookFolderContact_Collection.Count > 0 Then
                _onew_Delete.Delete(_Contacts_OutlookFolderContact_Collection)
            End If
            _onew_Delete.CommitChanges()

            Dim _Contacts_SysncOutlook As Contacts_SysncOutlook = _onew.CreateObject(Of Contacts_SysncOutlook)()
            _Contacts_SysncOutlook.IsFromOutlook = True
            _Contacts_SysncOutlook.SyscType = eSyscType.eFirstSync
            e.View = Application.CreateDetailView(_onew, "Contacts_SysncOutlook_DetailView", True, _Contacts_SysncOutlook)
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\NuvolarExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aContacts_SysncFromOutlook_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.PopupWindowShowActionExecuteEventArgs) Handles aContacts_SysncFromOutlook.Execute
        Try
            Frame.GetController(Of DevExpress.ExpressApp.Validation.PersistenceValidationController)().Active.SetItemValue("", False)
            Dim _ocur As Xpo.XPObjectSpace = View.ObjectSpace
            Dim _NeedCommitChanges As Boolean = False
            Dim _Contacts_SysncOutlook As Contacts_SysncOutlook = TryCast(e.PopupWindow.View.SelectedObjects(0), Contacts_SysncOutlook)
            Dim _OutlookApp As New Outlook.Application()
            Dim _OutlookNameSpace As Outlook.NameSpace = _OutlookApp.GetNamespace("MAPI")
            _OutlookNameSpace.Logon(, , False, True)
            Dim _ContactFolder As Outlook.MAPIFolder = _OutlookNameSpace.GetFolderFromID(_Contacts_SysncOutlook.Contacts_OutlookFolderContact.EntryID)

            Dim _ContactItem_Collection As Outlook.Items = _ContactFolder.Items
            _WaitFormClass.InitWork(0, 1, _ContactItem_Collection.Count)
            Select Case _Contacts_SysncOutlook.OverWriteDataType
                Case eOverWriteDataType.OverWriteOutlookData
                    For Each _ContactItem As Outlook.ContactItem In _ContactItem_Collection
                        _WaitFormClass.DoWork
                        Dim _Contacts As Contacts = _ocur.FindObject(Of Contacts)(CriteriaOperator.Parse("Oid=?", _ContactItem.User1))
                        If _Contacts Is Nothing Then
                            _ContactItem.Delete()
                        Else
                            Dim _FileName As String = String.Format("{0}{1}.jpg", Path.GetTempPath, _Contacts.Oid)
                            _ContactItem.FirstName = _Contacts.FirstName
                            _ContactItem.LastName = _Contacts.LastName
                            _ContactItem.Email1Address = _Contacts.Email
                            _ContactItem.Birthday = _Contacts.Birthday
                            _ContactItem.JobTitle = _Contacts.Position
                            _ContactItem.BusinessTelephoneNumber = _Contacts.BusinessTelephoneNumber
                            _ContactItem.BusinessFaxNumber = _Contacts.BusinessFaxNumber
                            _ContactItem.HomeFaxNumber = _Contacts.HomeFaxNumber
                            _ContactItem.MobileTelephoneNumber = _Contacts.MobileTelephoneNumber

                            If _Contacts.Photo IsNot Nothing Then
                                '_Contacts.Photo.Save(_FileName)
                                '_Contacts.ph()
                                _ContactItem.AddPicture(_FileName)
                            End If

                            If _Contacts.Address1 IsNot Nothing Then
                                _ContactItem.BusinessAddress = _Contacts.Address1.FullAddress
                                _ContactItem.BusinessAddressCity = _Contacts.Address1.City
                                _ContactItem.BusinessAddressCountry = _Contacts.Address1.Country.Name
                                _ContactItem.BusinessAddressPostalCode = _Contacts.Address1.ZipPostal
                                _ContactItem.BusinessAddressState = _Contacts.Address1.StateProvince
                                _ContactItem.BusinessAddressStreet = _Contacts.Address1.Street
                            End If

                            If _Contacts.Customers IsNot Nothing Then
                                _ContactItem.Companies = _Contacts.Customers.FullName
                                _ContactItem.CompanyName = _Contacts.Customers.Name
                            End If
                            If File.Exists(_FileName) Then File.Delete(_FileName)
                            _ContactItem.Save()
                        End If
                    Next
                Case eOverWriteDataType.OverWriteNuvolarData
                    For Each _ContactItem As Outlook.ContactItem In _ContactItem_Collection
                        _WaitFormClass.DoWork
                        Dim _Contacts As Contacts = _ocur.FindObject(Of Contacts)(CriteriaOperator.Parse("Oid=?", _ContactItem.User1))
                        If _Contacts Is Nothing Then _Contacts = New Contacts(_ocur.Session)
                        Dim _FileName As String = Path.GetTempPath + _Contacts.Oid.ToString + ".jpg"

                        With (_Contacts)
                            .FirstName = _ContactItem.FirstName
                            .LastName = _ContactItem.LastName
                            .Email = _ContactItem.Email1Address
                            .Birthday = _ContactItem.Birthday
                            .Position = _ContactItem.JobTitle
                            .BusinessTelephoneNumber = _ContactItem.BusinessTelephoneNumber
                            .BusinessFaxNumber = _ContactItem.BusinessFaxNumber
                            .HomeFaxNumber = _ContactItem.HomeFaxNumber
                            .MobileTelephoneNumber = _ContactItem.MobileTelephoneNumber

                            Dim _Address As New DevExpress.Persistent.BaseImpl.Address(_ocur.Session)
                            _Address.City = _ContactItem.BusinessAddressCity
                            Dim _Country As New DevExpress.Persistent.BaseImpl.Country(_ocur.Session)
                            _Country.Name = _ContactItem.BusinessAddressCountry
                            _Address.Country = _Country
                            _Address.ZipPostal = _ContactItem.BusinessAddressPostalCode
                            _Address.StateProvince = _ContactItem.BusinessAddressState
                            _Address.Street = _ContactItem.BusinessAddressStreet

                            .Address1 = _Address

                            If Not String.IsNullOrEmpty(_ContactItem.Companies) Then
                                Dim _Customers As Customers = _ocur.FindObject(Of Customers)(CriteriaOperator.Parse("FullName=?", _ContactItem.Companies))
                                If _Customers IsNot Nothing Then
                                    .Customers = _ocur.GetObject(_Customers)
                                End If
                            End If
                            .IsOutlookSync = True
                            .ContactItemFolderEntryID_Outlook = _Contacts_SysncOutlook.Contacts_OutlookFolderContact.EntryID
                        End With
                        _ocur.CommitChanges()
                        _ContactItem.User1 = _Contacts.Oid.ToString
                        _ContactItem.Save()
                    Next
            End Select
            If _NeedCommitChanges Then _ocur.CommitChanges()
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\NuvolarExceptions", "MsgBoxCheckItAgain")))
        Finally
            _Waitformclass.FinalWork
            Frame.GetController(Of DevExpress.ExpressApp.Validation.PersistenceValidationController)().Active.SetItemValue("", True)
        End Try
    End Sub
End Class
