Imports System.Management
Imports System.Net
Imports UTS_Core.Database
Imports UTS_Core.UTSModule
Imports UTS_Core.UTSModule.DbTableModel.Manage

Public Class ServiceConfig
    Private _privateIP As String

    Private _publicIP As String

    Private _mac As String

    Private ReadOnly _dsIndex As Integer

    Private ReadOnly _dsName As String

    Private ReadOnly _dsVerString As String

    Private _usVerString As String

    Private ReadOnly _usName As String

    Private _dsVer As Version

    Private _usVer As Version


    Sub New()
        _dsIndex = CInt(UtsRegistry.DataServiceIndex)
        _dsName = My.Application.Info.ProductName
        _dsVer = My.Application.Info.Version
        _dsVerString = My.Application.Info.Version.ToString
        _usName = UtsRegistry.UpdateServiceName
        _usVerString = UtsRegistry.UpdateServiceVersion
        If Version.TryParse(_usVerString, _usVer) = False Then
            _usVer = New Version(0, 0, 0, 0)
        End If

        BarnchNet = UtsRegistry.BarnchNet

        If Integer.TryParse(UtsRegistry.Roles, Roles) = False Then
            Roles = 0
        End If

        IsDBProxyConn = 0
        CacheCount = 0
        DbStatus = 0
        FtpStatus = 0
        NetworkNeiborhood = ""

        UsConnected = 0

        InitMacAndLocalIP()
    End Sub

    Public ReadOnly Property DsIndex() As Integer
        Get
            Return _dsIndex
        End Get
    End Property

    ''' <summary>
    ''' 数据服务的数据服务的名称
    ''' </summary>
    ''' <returns></returns>
    Public ReadOnly Property DsName() As String
        Get
            Return _dsName
        End Get
    End Property

    ''' <summary>
    ''' 数据服务的版本字符串
    ''' </summary>
    ''' <returns></returns>
    Public ReadOnly Property DsVerString() As String
        Get
            Return _dsVerString
        End Get
    End Property

    ''' <summary>
    ''' 更新服务的版本字符串
    ''' </summary>
    ''' <returns></returns>
    Public Property UsVerString() As String
        Get
            Return _usVerString
        End Get
        Set(value As String)
            _usVerString = value
            If Version.TryParse(_usVerString, _usVer) = False Then
                _usVer = New Version(0, 0, 0, 0)
            End If
        End Set
    End Property

    ''' <summary>
    ''' 数据服务的版本
    ''' </summary>
    ''' <returns></returns>
    Public ReadOnly Property DsVersion() As Version
        Get
            Return _dsVer
        End Get
    End Property

    ''' <summary>
    ''' 更新服务的版本
    ''' </summary>
    ''' <returns></returns>
    Public ReadOnly Property UsVersion() As Version
        Get
            Return _usVer
        End Get
    End Property

    ''' <summary>
    ''' 更新服务的名称
    ''' </summary>
    ''' <returns></returns>
    Public ReadOnly Property UsName() As String
        Get
            Return _usName
        End Get
    End Property

    ''' <summary>
    ''' 设备的局域网IP
    ''' </summary>
    ''' <returns></returns>
    Public ReadOnly Property PrivateIP() As String
        Get
            Return _privateIP
        End Get
    End Property

    ''' <summary>
    ''' 设备的MAC地址
    ''' </summary>
    ''' <returns></returns>
    Public ReadOnly Property Mac() As String
        Get
            Return _mac
        End Get
    End Property

    ''' <summary>
    ''' 与更新服务的连接状态
    ''' </summary>
    ''' <returns></returns>
    Public Property UsConnected As Integer

    ''' <summary>
    ''' 设备运行中产生的异常
    ''' </summary>
    ''' <returns></returns>
    Private Property ErrMsg As String


    ''' <summary>
    ''' 局域网中与主机的连接状态
    ''' </summary>
    ''' <returns></returns>
    Public Property IsDBProxyConn As Integer

    ''' <summary>
    ''' 设备加入的子网名称
    ''' </summary>
    ''' <returns></returns>
    Public Property BarnchNet As String

    ''' <summary>
    ''' 当前设备在局域网中的角色
    ''' </summary>
    ''' <returns></returns>
    Public Property Roles As Integer

    ''' <summary>
    ''' 网上邻居集合
    ''' </summary>
    ''' <returns></returns>
    Public Property NetworkNeiborhood As String

    ''' <summary>
    ''' 当前缓存表字段数量
    ''' </summary>
    ''' <returns></returns>
    Public Property CacheCount As Integer

    ''' <summary>
    ''' 云端数据库连接状态
    ''' </summary>
    ''' <returns></returns>
    Public Property DbStatus As Integer

    ''' <summary>
    ''' Ftp服务器连接状态
    ''' </summary>
    ''' <returns></returns>
    Public Property FtpStatus As Integer

    ''' <summary>
    ''' 私有IP地址变化
    ''' </summary>
    ''' <param name="ip"></param>
    Public Event PrivateIPChanged(ip As String)

    ''' <summary>
    ''' MAC地址变化
    ''' </summary>
    ''' <param name="mac"></param>
    Public Event MACChanged(mac As String)


    Public Sub UpdateErrMsg(type As String, msg As String)
        ErrMsg = $"{type},{msg}"
    End Sub

    ''' <summary>
    ''' 初始化MAC地址与获取本地IP
    ''' </summary>
    Public Sub InitMacAndLocalIP()
        ' Dim ip As String
        Dim mac As String
        Dim searcher As New ManagementObjectSearcher("select * from win32_NetworkAdapterConfiguration")
        Dim moc2 As ManagementObjectCollection = searcher.Get()
        For Each mo As ManagementObject In moc2
            If CBool(mo("IPEnabled")) Then
                mac = mo("MACAddress").ToString()
                If String.Compare(_mac, mac) <> 0 Then
                    _mac = mac
                    '触发MAC地址变化
                    RaiseEvent MACChanged(_mac)
                End If

                Dim a() As String = CType(mo("IpAddress"), String())

                Dim address As IPAddress = Nothing
                For Each ip As String In a
                    If IPAddress.TryParse(ip, address) Then

                        '使用IPV4地址
                        If address.AddressFamily = Sockets.AddressFamily.InterNetwork Then

                            If String.Compare(_privateIP, ip) <> 0 Then
                                '触发IP地址变化
                                _privateIP = ip
                                RaiseEvent PrivateIPChanged(_privateIP)
                            End If

                            Return
                        End If

                    End If
                Next
            End If
        Next
    End Sub

    ''' <summary>
    ''' 上传服务信息至数据库
    ''' </summary>
    Public Sub UpdateServiceInfo()
        Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
            db.Open()

            Dim cmdText As String
            Dim tbName As String = DataServiceListTable.TableName
            Dim filed As New Dictionary(Of String, String)
            filed.Add($"{DataServiceListTable.ColNames.ServiceVersion}", DsVerString)
            filed.Add($"{DataServiceListTable.ColNames.CacheCount}", CacheCount.ToString)
            filed.Add($"{DataServiceListTable.ColNames.IsDBProxyConn}", IsDBProxyConn.ToString)
            filed.Add($"{DataServiceListTable.ColNames.NetworkNeiborhood}", NetworkNeiborhood)

            If String.IsNullOrEmpty(ErrMsg) = False Then
                filed.Add($"{DataServiceListTable.ColNames.ErrMsg}", ErrMsg)
                ErrMsg = String.Empty
            End If

            Dim condition As String = $"`{DataServiceListTable.ColNames.ID}` = {_dsIndex}"
            cmdText = db.CmdHelper.DbUpdate(UtsDb.RemotePublicDb, tbName, filed, condition)

            Try
                db.ExecuteNonQuery(cmdText)
            Catch ex As Exception
                ServiceLog.WriteErrorLog($"Update ServiceTable Error:{ex.Message}")
            End Try

            db.Close()
        End Using
    End Sub
End Class
