Imports UTS_Core.UTSModule.Service

''' <summary>
''' 服务任务列表,管理服务的所有任务
''' </summary>
Public Class ServiceTasks
    Private ReadOnly _tasks As Dictionary(Of String, ServiceTask)

    Public Event AddTask(task As Dictionary(Of String, String))
    Public Event UpdateTask(task As Dictionary(Of String, String))
    Public Event DelTask(task As String)
    Public Event ClearTask()



    Sub New()
        _tasks = New Dictionary(Of String, ServiceTask)()

    End Sub

    ''' <summary>
    ''' 任务总数
    ''' </summary>
    ''' <returns></returns>
    Public Function Count() As Integer
        Return _tasks.Count
    End Function

    ''' <summary>
    ''' 获取所有的服务任务
    ''' </summary>
    ''' <returns></returns>
    Public Function GetAllServiceTasks() As List(Of ServiceTask)
        Return _tasks.Values.ToList()
    End Function


    ''' <summary>
    ''' 添加任务,默认开启任务
    ''' </summary>
    Public Sub Add(task As ServiceTask, Optional start As Boolean = True)
        If String.IsNullOrEmpty(task.TaskName) Then '无效的任务名
            Throw New Exception($"TaskName {task.TaskName} is invalid!")
        End If

        If _tasks.ContainsKey(task.TaskName) Then '已存在的任务名
            Throw New Exception($"TaskName {task.TaskName} already exists!")
        End If

        _tasks.Add(task.TaskName, task)
        If start Then task.Start() '默认添加任务时，开启任务
        RaiseEvent AddTask(task.GetParams())
    End Sub

    ''' <summary>
    ''' 添加任务，默认开启服务
    ''' </summary>
    Public Sub Add(taskInfo As Dictionary(Of String, String), Optional start As Boolean = True)
        If taskInfo.ContainsKey("Type") AndAlso taskInfo.ContainsKey("Name") Then
            Dim task As ServiceTask
            Select Case taskInfo("Type")'根据类型进行不同任务的初始化
                Case $"{ ServiceTask.ServiceTaskTypeEnum.DbSync}"
                    task = New DbSyncServiceTask(taskInfo("Name"), taskInfo)
                    Add(task, start)
                    ServiceLog.WriteInfoLog($"taskParam:{task.TaskName}  {task.TaskStatus} {task.TaskType}")
                Case $"{ ServiceTask.ServiceTaskTypeEnum.ListenJsonFile}"
                    task = New ListenJsonFileServiceTask(taskInfo("Name"), taskInfo)
                    Add(task, start)
                Case Else
                    Throw New Exception($"Unknown Type:{taskInfo("Type")}")
            End Select
        Else
            Throw New Exception($"AddTask Invalid TaskInfo")
        End If
    End Sub


    ''' <summary>
    ''' 添加任务列表
    ''' </summary>
    ''' <param name="tasks"></param>
    Public Sub AddRange(tasks As List(Of ServiceTask), Optional start As Boolean = True)
        For Each task As ServiceTask In tasks
            Add(task, start)
        Next
    End Sub


    ''' <summary>
    ''' 移除指定的服务任务
    ''' </summary>
    ''' <param name="task"></param>
    Sub Remove(task As ServiceTask)
        If _tasks.ContainsKey(task.TaskName) Then
            task.Stop()
            RaiseEvent DelTask(task.TaskName)
            _tasks.Remove(task.TaskName)
        End If
    End Sub

    ''' <summary>
    ''' 移除指定名称的服务任务
    ''' </summary>
    Sub RemoveAt(taskName As String)
        If _tasks.ContainsKey(taskName) Then
            Remove(_tasks.Item(taskName))
        End If
    End Sub

    ''' <summary>
    ''' 清空所有的服务任务
    ''' </summary>
    Sub Clear()
        '关闭所有任务
        For Each task As KeyValuePair(Of String, ServiceTask) In _tasks
            task.Value.Stop()
        Next

        '清空任务列表
        _tasks.Clear()
        RaiseEvent ClearTask()
    End Sub


    ''' <summary>
    ''' 设置指定任务的任务参数
    ''' </summary>
    ''' <param name="taskName"></param>
    ''' <param name="param"></param>
    Public Sub SetTaskParams(taskName As String, param As Dictionary(Of String, String))
        If _tasks.ContainsKey(taskName) = False Then '不存在的任务
            Throw New Exception($"TaskName {taskName} is nonexistent!")
        End If
        _tasks.Item(taskName).SetParams(param)
        RaiseEvent UpdateTask(_tasks.Item(taskName).GetParams())
    End Sub


    ''' <summary>
    ''' 返回指定任务名称的任务参数
    ''' </summary>
    ''' <param name="taskName"></param>
    ''' <returns></returns>
    Public Function GetTaskParams(taskName As String) As Dictionary(Of String, String)
        If _tasks.ContainsKey(taskName) = False Then '不存在的任务
            Throw New Exception($"TaskName {taskName} is nonexistent!")
        End If
        Return _tasks.Item(taskName).GetParams()
    End Function


    ''' <summary>
    ''' 获取所有任务的参数信息
    ''' </summary>
    ''' <returns></returns>
    Public Function GetAllTasksParam() As List(Of Dictionary(Of String, String))
        Dim allParams As New List(Of Dictionary(Of String, String))
        For Each task As KeyValuePair(Of String, ServiceTask) In _tasks
            allParams.Add(task.Value.GetParams())
        Next
        Return allParams
    End Function

    Public Sub StartTask(taskName As String)
        If _tasks.ContainsKey(taskName) = False Then '不存在的任务
            Throw New Exception($"TaskName {taskName} is nonexistent!")
        End If

        _tasks.Item(taskName).Start()
        RaiseEvent UpdateTask(_tasks.Item(taskName).GetParams())
    End Sub

    ''' <summary>
    '''开启所有任务
    ''' </summary>
    Public Sub StartAllTasks()
        For Each task As KeyValuePair(Of String, ServiceTask) In _tasks
            task.Value.Start()
            RaiseEvent UpdateTask(task.Value.GetParams())
        Next
    End Sub


    ''' <summary>
    ''' 结束休眠,立即执行任务
    ''' </summary>
    ''' <param name="taskName"></param>
    Public Sub RestartTask(taskName As String)
        If _tasks.ContainsKey(taskName) = False Then '不存在的任务
            Throw New Exception($"TaskName {taskName} is nonexistent!")
        End If

        _tasks.Item(taskName).Restart()
        RaiseEvent UpdateTask(_tasks.Item(taskName).GetParams())
    End Sub

    ''' <summary>
    '''开启所有任务
    ''' </summary>
    Public Sub RestartAllTasks()
        For Each task As KeyValuePair(Of String, ServiceTask) In _tasks
            task.Value.Restart()
            RaiseEvent UpdateTask(task.Value.GetParams())
        Next
    End Sub


    ''' <summary>
    ''' 停止指定任务名的任务
    ''' </summary>
    ''' <param name="taskName"></param>
    Public Sub StopTask(taskName As String)
        If _tasks.ContainsKey(taskName) = False Then '不存在的任务
            Throw New Exception($"TaskName {taskName} is nonexistent!")
        End If

        _tasks.Item(taskName).Stop()
        RaiseEvent UpdateTask(_tasks.Item(taskName).GetParams())
    End Sub

    ''' <summary>
    '''停止所有任务
    ''' </summary>
    Public Sub StopAllTasks()
        For Each task As KeyValuePair(Of String, ServiceTask) In _tasks
            task.Value.Stop()
            RaiseEvent UpdateTask(task.Value.GetParams())
        Next
    End Sub
End Class