Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Configuration
Imports DevExpress.Persistent.Base
Imports DevExpress.ExpressApp
Imports System.Collections
Imports DevExpress.ExpressApp.Xpo
Imports System.ServiceModel
Imports System.Runtime.Remoting.Channels
Imports System.Security.Principal
Imports System.Threading
Imports DevExpress.Persistent.BaseImpl
Imports DevExpress.Persistent.AuditTrail

Imports RabbitMQ.Client
Imports RabbitMQ.ServiceModel
Imports RabbitMQ.Client.Events
Imports Newtonsoft.Json
Imports DevExpress.Xpo
Imports SISBusiness.Module
Imports DevExpress.Data.Filtering
Imports System.Xml
Imports System.IO
Imports System.Collections.Specialized
Imports SISBusiness.RabbitMQ.Module

Friend Class Program
    Private Shared _Session As DevExpress.Xpo.Session

    Private Shared _TimerCore As System.Threading.Timer
    Private Shared _Semaphor As Boolean = True
    Private Shared _ErrorLogPath As String
    Private Shared _StatLogPath As String
    Shared Sub Main(ByVal args() As String)
        Dim _ErrorFileHandling As String() = (ConfigurationManager.AppSettings("ErrorLogPath")).Split(New Char() {";"c})

        If _ErrorFileHandling(0).Replace("Path=", "") = "CurrentDirectory" Then
            _ErrorLogPath = Environment.CurrentDirectory + _ErrorFileHandling(1).Replace("FileName=", "")
        Else
            _ErrorLogPath = _ErrorFileHandling(0).Replace("Path=", "") + _ErrorFileHandling(1).Replace("FileName=", "")
        End If
        Dim _RunningMode As String = ConfigurationManager.AppSettings("RunningMode")

        _Session = LoginSession()

        If _Session IsNot Nothing Then
            If _Session.IsConnected Then

                Select Case _RunningMode
                    Case "0" 'Olvas
                        Try
                            Console.WriteLine("SIS Business RabbitMQ console application version 1.2.10234, XAF Version: 12.2.11, RabbitMQ version: 3.2.1")
                            Console.WriteLine(_ErrorLogPath)
                            ValueManager.ValueManagerType = GetType(MultiThreadValueManager(Of )).GetGenericTypeDefinition()

                            Dim _Factory_HostName As String = ConfigurationManager.AppSettings("Factory_HostName")
                            Dim _Factory_UserName As String = ConfigurationManager.AppSettings("Factory_UserName")
                            Dim _Factory_Password As String = ConfigurationManager.AppSettings("Factory_Password")
                            Dim _Factory_VirtualHost As String = ConfigurationManager.AppSettings("Factory_VirtualHost")

                            Dim _Queue_Name As String = ConfigurationManager.AppSettings("Queue_Name")

                            Console.WriteLine("Starting...")

                            Dim _factory As RabbitMQ.Client.ConnectionFactory
                            Dim _connection As RabbitMQ.Client.IConnection
                            Dim _channel As RabbitMQ.Client.IModel
                            Dim _consumer As EventingBasicConsumer


                            _factory = New ConnectionFactory
                            _factory.HostName = _Factory_HostName
                            _factory.UserName = _Factory_UserName
                            _factory.Password = _Factory_Password
                            _factory.VirtualHost = _Factory_VirtualHost
                            _factory.RequestedChannelMax = 10

                            _connection = _factory.CreateConnection
                            _channel = _connection.CreateModel

                            Console.WriteLine("Setup...")

                            _consumer = New EventingBasicConsumer


                            AddHandler _consumer.Received, AddressOf Consumer_Received

                            Console.WriteLine("Starting server pool...")

                            ' _channel.BasicConsume(_Queue_Name, False, _consumer) 'Fenthagyni a queue-ban
                            _channel.BasicConsume(_Queue_Name, True, _consumer) 'Leszedni a queue-ból 

                            Console.WriteLine("Server is started. Press Enter to stop.")
                            Console.ReadLine()
                            Console.WriteLine("Stopping...")

                            '_channel.Dispose()
                            _channel.Close()
                            _connection.Close()

                            Console.WriteLine("Server is stopped.")

                        Catch e As Exception
                            Console.WriteLine("Exception occurs: " & e.Message)
                            Console.WriteLine("Press Enter to close.")
                            Console.ReadLine()
                        End Try
                    Case "1" 'Küld
                        Try
                            Console.WriteLine("SIS Business RabbitMQ console application version 1.2.10234, XAF Version: 12.2.11, RabbitMQ version: 3.2.1")
                            ValueManager.ValueManagerType = GetType(MultiThreadValueManager(Of )).GetGenericTypeDefinition()

                            Console.WriteLine("Starting...")

                            Console.WriteLine("Setup...")
                            _TimerCore = New System.Threading.Timer(AddressOf _TimerCore_Tick, Nothing, 0, 10000)

                            Console.WriteLine("Starting server send...")

                            Console.WriteLine("Server is started. Press Enter to stop.")
                            Console.ReadLine()
                            Console.WriteLine("Stopping...")

                            Console.WriteLine("Server is stopped.")
                        Catch e As Exception
                            Console.WriteLine("Exception occurs: " & e.Message)
                            Console.WriteLine("Press Enter to close.")
                            Console.ReadLine()
                        End Try
                    Case "2" 'Mindkettő

                    Case Else
                        'Gáz van

                End Select
            End If
        End If
    End Sub
    Private Shared Sub Consumer_Received(sender As IBasicConsumer, args As BasicDeliverEventArgs)

        Try
            If _Session IsNot Nothing Then
                Dim _JSONText As String = Encoding.UTF8.GetString(args.Body)
                Dim _XML As System.Xml.XmlDocument = JsonConvert.DeserializeXmlNode(_JSONText, "JsonXML")

                If _XML IsNot Nothing Then
                    Dim _method As String = _XML.SelectSingleNode("JsonXML/method").InnerText

                    If _method.Contains("ugyfelimport") Then GetCustomers.CustomerImport(_XML, "JsonXML/params", "", _Session, True)
                    If _method.Contains("szamlaimport") Then GetGLAccounts.GLAccountImport(_XML, "", _Session, True)
                    If _method.Contains("get_version") Then SISVersion.SendSISVersion(_XML, args.BasicProperties)
                End If
            Else
                Throw New Exception(String.Format("Nem lehet csatlakozni az SQL serverhez. ConnenctionString:{0}", ConfigurationManager.ConnectionStrings.Item("ConnectionString").ConnectionString))
            End If
        Catch ex As Exception
            WriteErrorLog((Now + " " + ex.Message).ToString, _ErrorLogPath)
        End Try
    End Sub
    Private Shared Sub _TimerCore_Tick(ByVal state As Object)
        _TimerCore.Change(Timeout.Infinite, 0)
        Console.WriteLine("Küldés : " + Now)
        PublishCustomers.PublishCustomers(_ErrorLogPath, _Session)
        _TimerCore.Change(0, 10000)
    End Sub
    Private Shared Function LoginSession() As DevExpress.Xpo.Session
        Dim _Session As New DevExpress.Xpo.Session

        _Session.ConnectionString = ConfigurationManager.ConnectionStrings.Item("ConnectionString").ConnectionString
        _Session.Connect()

        If Not _Session.IsConnected Then
            _Session = Nothing
        End If

        Return _Session
    End Function
    Private Shared Sub LogoffSession(_Session As DevExpress.Xpo.Session)
        _Session.Connection.Close()
    End Sub
End Class

