Imports System
Imports System.IO
Imports System.Configuration
Imports DevExpress.Persistent.Base

Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports DevExpress.ExpressApp
Imports System.Collections
Imports DevExpress.ExpressApp.Xpo
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 DevExpress.Data.Filtering
Imports System.Xml
Imports System.Collections.Specialized
Imports SISBusiness.RabbitMQ.Module

Public Class WinService
    Inherits System.ServiceProcess.ServiceBase

    Private _Session As DevExpress.Xpo.Session

    Dim _TimerCore As System.Threading.Timer
    Dim _Semaphor As Boolean = True
    Dim _RunningMode As String = ConfigurationManager.AppSettings("RunningMode")

    Dim _factory As ConnectionFactory
    Dim _connection As IConnection
    Dim _channel As IModel
    Dim _consumer As EventingBasicConsumer

    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Diagnostics.EventLog.WriteEntry(ConfigurationManager.AppSettings("ServiceName"), "Service Start at " + Now.ToString)

        _Session = LoginSession()
        Try
            If _Session IsNot Nothing Then
                If _Session.IsConnected Then
                    Select Case _RunningMode
                        Case "0" 'Olvas
                            Try
                                '   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")

                                _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

                                _consumer = New EventingBasicConsumer

                                AddHandler _consumer.Received, AddressOf Consumer_Received

                                '   Diagnostics.EventLog.WriteEntry(ConfigurationManager.AppSettings("ServiceName"), "Starting server pool at " + Now.ToString)

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

                            Catch e As Exception
                                'Diagnostics.EventLog.WriteEntry(ConfigurationManager.AppSettings("ServiceName"), e.Message)
                            End Try
                        Case "1" 'Küld
                            Try
                                '   ValueManager.ValueManagerType = GetType(MultiThreadValueManager(Of )).GetGenericTypeDefinition()

                                _TimerCore = New System.Threading.Timer(AddressOf _TimerCore_Tick, Nothing, 0, 10000)

                            Catch e As Exception
                                'Diagnostics.EventLog.WriteEntry(ConfigurationManager.AppSettings("ServiceName"), e.Message)
                            End Try
                        Case "2" 'Mindkettő

                        Case Else
                            'Gáz van

                    End Select
                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
            'Diagnostics.EventLog.WriteEntry(ConfigurationManager.AppSettings("ServiceName"), ex.Message)
        End Try
    End Sub
    Protected Overrides Sub OnStop()
        Select Case _RunningMode
            Case "0" 'Olvas
                _channel.Close()
                _connection.Close()
            Case "1"
                _TimerCore.Change(Timeout.Infinite, 0)
                _TimerCore.Dispose()
            Case "2"
        End Select

        If _Session.IsConnected Then LogoffSession(_Session)

        ' Diagnostics.EventLog.WriteEntry(ConfigurationManager.AppSettings("ServiceName"), "Service STOP")
    End Sub
    Private Sub Consumer_Received(sender As IBasicConsumer, args As BasicDeliverEventArgs)
        '// Itt afogadás
        'Console.WriteLine("Fogadás...")

        Try
            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
        Catch ex As Exception
            WriteErrorLog((Now + " " + ex.Message).ToString, "")
        End Try
    End Sub
    Private Sub _TimerCore_Tick(ByVal state As Object)
        _TimerCore.Change(Timeout.Infinite, 0)
        PublishCustomers.PublishCustomers("", _Session, True)
        _TimerCore.Change(0, 10000)
    End Sub
    Private Function LoginSession() As DevExpress.Xpo.Session
        Dim _Session As New DevExpress.Xpo.Session

        _Session.ConnectionString = ConfigurationManager.ConnectionStrings.Item("ConnectionString").ConnectionString
        _Session.AutoCreateOption = DB.AutoCreateOption.None
        _Session.Connect()

        If Not _Session.IsConnected Then
            _Session = Nothing
        End If

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

End Class
