Public Class UtsAppManager
    ''' <summary>
    ''' 设备运行APP列表,键为APP名称，值为App对象
    ''' </summary>
    Private _appDic As Dictionary(Of String, UtsApp)

    Private _clientDic As Dictionary(Of Net.Sockets.TcpClient, UtsApp)

    Sub New()
        _appDic = New Dictionary(Of String, UtsApp)
        _clientDic = New Dictionary(Of Net.Sockets.TcpClient, UtsApp)
    End Sub

    Public Sub AddApp(app As UtsApp)
        If _appDic.ContainsKey(app.Name) = False Then
            _appDic.Add(app.Name, app)
        End If
    End Sub

    ''' <summary>
    ''' 判断App是否存在队列中
    ''' </summary>
    ''' <param name="appName"></param>
    ''' <returns></returns>
    Public Function AppExists(appName As String) As Boolean
        Return _appDic.ContainsKey(appName)
    End Function

    ''' <summary>
    ''' 获取UtsApp对象，没有则添加对象至队列后再返回
    ''' </summary>
    ''' <param name="appName"></param>
    ''' <returns></returns>
    Public Function GetApp(appName As String) As UtsApp
        Static lock As New Object

        SyncLock lock
            If _appDic.ContainsKey(appName) = False Then
                ServiceLog.WriteDebugLog($"{appName} Add!")
                _appDic.Add(appName, New UtsApp())
            End If
        End SyncLock

        Return _appDic(appName)
    End Function

    ''' <summary>
    ''' 获取当前App列表
    ''' </summary>
    ''' <returns></returns>
    Public Function GetAllApps() As List(Of UtsApp)
        Return _appDic.Values.ToList()
    End Function

    Public Function GetClientBindApp(client As Net.Sockets.TcpClient) As UtsApp
        If _clientDic.ContainsKey(client) Then
            Return _clientDic(client)
        Else
            Return Nothing
        End If
    End Function

    Public Sub BindClientAndApp(client As Net.Sockets.TcpClient, app As UtsApp)
        Static lock As New Object

        SyncLock lock
            If _clientDic.ContainsKey(client) = False Then
                _clientDic.Add(client, app)
                ServiceLog.WriteDebugLog($"{_clientDic(client).Name} Connect!")
            End If
        End SyncLock
    End Sub


    Public Sub CancelClientBind(client As Net.Sockets.TcpClient)
        If _clientDic.ContainsKey(client) Then
            ServiceLog.WriteDebugLog($"{_clientDic(client).Name} Disconnect!")
            _clientDic(client).Status = UtsApp.AppStatus.Closed
            _clientDic(client).Client = Nothing
            _clientDic.Remove(client)
        End If
    End Sub
End Class
