Imports DevExpress.Xpo
Imports System.Configuration
Imports SISBusiness.Module
Imports DevExpress.Data.Filtering
Imports System.Threading
Imports RabbitMQ.Client


Public Module PublishCustomers
    Public Sub PublishCustomers(_errorLogFile As String, _Session As DevExpress.Xpo.Session, Optional IsService As Boolean = False)
        Try
            If _Session IsNot Nothing Then
                Dim _Customers As Customers = Nothing
                If _Session.IsConnected Then
                    Dim _uow As New UnitOfWork(_Session.DataLayer)
                    ' Dim _Customers_Collection As New XPCollection(Of Customers)(_uow, CriteriaOperator.Parse("IsNull(Oid_DH)=False AND Oid_DH<>'' AND ObjectChanged > QueueUpdated")) 'CriteriaOperator.Parse("ObjectChanged>QueueUpdated"))
                    Dim _Customers_Collection As New XPCollection(Of Customers)(_uow, CriteriaOperator.Parse("ObjectChanged > QueueUpdated")) 'CriteriaOperator.Parse("ObjectChanged>QueueUpdated"))
                    If _Customers_Collection.Count > 0 Then
                        Dim _factory As ConnectionFactory
                        Dim _connection As IConnection
                        Dim _channel As IModel

                        _factory = New ConnectionFactory
                        _factory.HostName = ConfigurationManager.AppSettings("Factory_HostName")
                        _factory.UserName = ConfigurationManager.AppSettings("Factory_UserName")
                        _factory.Password = ConfigurationManager.AppSettings("Factory_Password")
                        _factory.VirtualHost = ConfigurationManager.AppSettings("Factory_VirtualHost")

                        _connection = _factory.CreateConnection
                        _channel = _connection.CreateModel

                        Dim _Exchange_Name = ConfigurationManager.AppSettings("Exchange_Name")
                        Dim _Exchange_RoutingKey As String = ConfigurationManager.AppSettings("Exchange_RoutingKey")
                        Dim _IBasicProperties As IBasicProperties = _channel.CreateBasicProperties

                        For Each _Customers In _Customers_Collection
                            If _Customers.ObjectChanged > _Customers.QueueUpdated Then
                                Dim _Text4Send As String = CreateCustomerText(_Customers, _uow, _errorLogFile)
                                Dim uTime As Integer
                                uTime = (DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds

                                _IBasicProperties.Timestamp = New AmqpTimestamp(uTime)
                                _IBasicProperties.MessageId = Guid.NewGuid().ToString
                                _IBasicProperties.ContentType = "application/json"
                                _IBasicProperties.ContentEncoding = "UTF-8"


                                _IBasicProperties.Headers = New Collections.Generic.Dictionary(Of String, Object)
                                _IBasicProperties.Headers.Add("mq3c-message-type", "MQ3CMessage_JSON_RPC")

                                _channel.BasicPublish(_Exchange_Name, _Exchange_RoutingKey, _IBasicProperties, StrToByteArray(_Text4Send))
                                _Customers.QueueUpdated = GetSQLTime(_uow)
                                _Customers.Save()
                                _uow.CommitChanges()
                                If IsService Then
                                    '    Diagnostics.EventLog.WriteEntry(ConfigurationManager.AppSettings("ServiceName"), "Küldés: [Customer: " + _Customers.Oid_DH + "]")
                                End If
                            End If
                        Next
                        _channel.Close()
                        _connection.Close()
                    End If
                End If
            End If
        Catch ex As Exception
            If IsService Then
                'Diagnostics.EventLog.WriteEntry(ConfigurationManager.AppSettings("ServiceName"), "Küldés HIBA : " + ex.Message)
            Else
                WriteErrorLog(Now + " : " + ex.Message, _errorLogFile)
            End If

        Finally

        End Try
    End Sub
    Public Function StrToByteArray(str As String) As Byte()
        Dim encoding As New System.Text.UTF8Encoding()
        Return encoding.GetBytes(str)
    End Function
    Private Function CreateCustomerText(_Customers As Customers, _Session As Session, _errorLogFile As String) As String
        Dim _CustomersText As String = ""
        Try
            _CustomersText += "{""jsonrpc"":""2.0"",""method"":""ugyfelimport"",""params"":{ ""ugyfel"":{"
            _CustomersText += """id"":""" + _Customers.Oid_DH + ""","
            _CustomersText += """ugyfelszam"":""" + _Customers.CustomerNumber + ""","
            '_CustomersText += """kulsougyfelazonosito"":"""","
            _CustomersText += """nev"":""" + _Customers.Name + ""","
            '_CustomersText += """nev"":""" + "ÁRVÍZTŰRŐTÜKÖRFÚRÓGÉP árvíztűrőtükörfúrógép" + ""","
            If _Customers.Address1 IsNot Nothing Then
                If _Customers.Address1.Country IsNot Nothing Then
                    _CustomersText += """orszag"":""" + _Customers.Address1.Country.Name + ""","
                Else
                    _CustomersText += """orszag"":"""","
                End If
                _CustomersText += """varos"":""" + _Customers.Address1.City + ""","
                '_CustomersText += """emajto"":"""","
                _CustomersText += """irszam"":""" + _Customers.Address1.ZipPostal + ""","
                _CustomersText += """utca"":""" + _Customers.Address1.Street + ""","
            Else
                _CustomersText += """orszag"":"""","
                _CustomersText += """varos"":"""","
                ''_CustomersText += """emajto"":"""","
                _CustomersText += """irszam"":"""","
                _CustomersText += """utca"":"""","
            End If

            '_CustomersText += """hazszam"":"""","
            '_CustomersText += """szigsz"":"""","
            '_CustomersText += """jogositvanyszam"":"""","
            '_CustomersText += """utlevelszam"":"""","
            '_CustomersText += """lakcimkartyaszam"":"""","
            If _Customers.MotherName IsNot Nothing Then
                _CustomersText += """anyjaneve"":""" + _Customers.MotherName + ""","
            Else
                _CustomersText += """anyjaneve"":"""","
            End If
            _CustomersText += """szuletesidatum"":""" + Format(_Customers.BirthDate.Date, "yyyy-MM-dd") + ""","
            If _Customers.BirthAddress IsNot Nothing Then
                _CustomersText += """szuletesihely"":""" + _Customers.BirthAddress.City + ""","
            Else
                _CustomersText += """szuletesihely"":"""","
            End If
            '_CustomersText += """szuletesinev"":"""","
            '_CustomersText += """meghatalmazott_nev"":"""","
            '_CustomersText += """meghatalmazott_szuletesinev"":"""","
            '_CustomersText += """meghatalmazott_anyjaneve"":"""","
            '_CustomersText += """meghatalmazott_szigsz"":"""","
            '_CustomersText += """meghatalmazott_jogositvanyszam"":"""","
            '_CustomersText += """meghatalmazott_utlevelszam"":"""","
            '_CustomersText += """meghatalmazott_lakcimkartyaszam"":"""","
            '_CustomersText += """telefonszam"":"""","
            '_CustomersText += """fax"":"""","
            _CustomersText += """email"":""" + _Customers.Email + ""","
            ''_CustomersText += """eszamla_email"":"""","
            _CustomersText += """megjegyzes"":""" + _Customers.Description + ""","
            '_CustomersText += """kiemelt"":"""","
            '_CustomersText += """letrehozva"":"""","
            '_CustomersText += """letrehozta"":"""","
            '_CustomersText += """modositva"":"""","
            '_CustomersText += """modositotta"":"""","
            '_CustomersText += """torolve"":"""","
            '_CustomersText += """torolte"":"""","
            '_CustomersText += """jelleg"":"""","
            _CustomersText += """cegjegyzekszam"":""" + _Customers.CompanyRegistrationNumber + ""","
            If _Customers.VATNumber IsNot Nothing Then
                _CustomersText += """adoszam"":""" + _Customers.VATNumber + ""","
            Else
                _CustomersText += """adoszam"":"""","
            End If
            '_CustomersText += """belsomegjegyzes"":"""","
            '_CustomersText += """levelezesinev"":"""","
            'If _Customers.Address2 IsNot Nothing Then
            '    If _Customers.Address2.Country IsNot Nothing Then
            '        _CustomersText += """levelezesiorszag"":""" + _Customers.Address2.Country.Name + ""","
            '    Else
            '        _CustomersText += """levelezesiorszag"":"""","
            '    End If

            '    _CustomersText += """levelezesivaros"":""" + _Customers.Address2.City + ""","
            '    _CustomersText += """levelezesiemajto"":"""","
            '    _CustomersText += """levelezesiutca"":""" + _Customers.Address2.Street + ""","
            '    _CustomersText += """levelezesihazszam"":"""","
            '    _CustomersText += """levelezesiirszam"":""" + _Customers.Address2.ZipPostal + ""","
            'Else
            '    _CustomersText += """levelezesiorszag"":"""","
            '    _CustomersText += """levelezesivaros"":"""","
            '    _CustomersText += """levelezesiemajto"":"""","
            '    _CustomersText += """levelezesiutca"":"""","
            '    _CustomersText += """levelezesihazszam"":"""","
            '    _CustomersText += """levelezesiirszam"":"""","
            'End If
            If _Customers.CanUseMarketingInfo Then
                _CustomersText += """adataimarketingcelrahasznalhatok"":""1"","
            Else
                _CustomersText += """adataimarketingcelrahasznalhatok"":""0"","
            End If
            If _Customers.CanUseMarketingInfoThirdParts Then
                _CustomersText += """adataimarketingcelraharmadikfelnekkiadhatok"":""1"","
            Else
                _CustomersText += """adataimarketingcelraharmadikfelnekkiadhatok"":""0"","
            End If
            '_CustomersText += """telefonszam2"":"""","
            '_CustomersText += """telefonszam3"":"""","
            '_CustomersText += """szorszag"":"""","
            '_CustomersText += """sznev"":"""","
            '_CustomersText += """szadoszam"":"""","
            '_CustomersText += """szvaros"":"""","
            '_CustomersText += """szemajto"":"""","
            '_CustomersText += """szutca"":"""","
            '_CustomersText += """szhazszam"":"""","
            '_CustomersText += """szirszam"":"""","
            '_CustomersText += """ugyfeljutalek"":"""","
            '_CustomersText += """befizeteskonyvelendo"":"""","
            '_CustomersText += """email_penzugy"":"""","
            '_CustomersText += """iszamla_ugyfelazon"":"""","
            '_CustomersText += """felszolitando"":"""","
            '_CustomersText += """hangbemondastartozas"":"""","
            '_CustomersText += """megjegyzes_szamlara"":"""","
            '_CustomersText += """kapcsolattarto"":"""","
            '_CustomersText += """viszonteladokod"":"""","
            '_CustomersText += """viszontelado"":"""","
            '_CustomersText += """vevo"":"""","
            '_CustomersText += """szallito"":"""","
            '_CustomersText += """konyvelesi_parameter"":"""","
            '_CustomersText += """partner_ugyfelszam"":"""","
            '_CustomersText += """partner_viszonteladokod"":"""","
            '_CustomersText += """partner_nev"":"""","
            '_CustomersText += """szulo_ugyfel_ugyfelszam"":"""","
            '_CustomersText += """szulo_ugyfel_viszonteladokod"":"""","
            '_CustomersText += """szulo_ugyfel_nev"":"""","
            '_CustomersText += """terulet"":"""","
            _CustomersText += """sis_oid"":""" + _Customers.Oid.ToString + ""","
            _CustomersText += """bankszamlaszamok"":{"

            Dim _Index As Long = 0
            For Each _CustomerBankAccounts As CustomerBankAccounts In _Customers.CustomerBankAccounts
                _CustomersText += """" + CInt(Math.Ceiling(Rnd() * 100000)).ToString + """: {"
                '_CustomersText += """id"": """","
                _CustomersText += """bankszamlaszam"": """ + _CustomerBankAccounts.AccountNumber + """"
                '_CustomersText += """szamlatulajdonos"": """","
                '_CustomersText += """megjegyzes"": """","
                If _Index = (_Customers.CustomerBankAccounts.Count - 1) Then
                    _CustomersText += "}"
                Else
                    _CustomersText += "},"
                End If
                _Index += 1
            Next

            _CustomersText += "}" 'bankszámlaszámok vége vége
            _CustomersText += "}},""MQ3CMessage_JSON_RPC"":{"

            _CustomersText += "}}" 'params vége és utolsó szekció
        Catch ex As Exception
            WriteErrorLog(Now + " : " + ex.Message, _errorLogFile)
            _CustomersText = ""
        End Try
        Return _CustomersText
    End Function
End Module
