Imports System.Threading
Imports System.Xml.Serialization
Imports UTS_Core.UTSModule.Service

<XmlInclude(GetType(ListenJsonFileServiceTask))>
Public Class ListenJsonFileServiceTask
    Inherits ServiceTask

    Private ReadOnly _jsonFile As JsonFileListen

    Sub New()
        TaskType = ServiceTaskTypeEnum.ListenJsonFile
        TaskStatus = ServiceTaskStatusEnum.Stop
        TaskName = "ListenJsonFile"

        _jsonFile = New JsonFileListen()
    End Sub

    Sub New(name As String)
        TaskType = ServiceTaskTypeEnum.ListenJsonFile
        TaskStatus = ServiceTaskStatusEnum.Stop
        TaskName = name

        _jsonFile = New JsonFileListen()
    End Sub

    Sub New(name As String, param As Dictionary(Of String, String))
        TaskType = ServiceTaskTypeEnum.ListenJsonFile
        TaskStatus = ServiceTaskStatusEnum.Stop
        TaskName = name

        _jsonFile = New JsonFileListen()

        SetParams(param)


    End Sub


    ''' <summary>
    ''' 具体的执行过程
    ''' </summary>
    ''' <param name="stat">状态值,暂未启用</param>
    Private Sub StartCallback(stat As Object)
        While TaskStatus = ServiceTaskStatusEnum.Start
            ServiceLog.WriteInfoLog($"SyncTask Wait Timeout.")

            '等待任务
            Dim lastTime As DateTime = Now
            While (Now - lastTime).TotalMinutes < Interval
                If TaskStatus = ServiceTaskStatusEnum.Stop Then
                    Return
                End If

                Thread.Sleep(1000)
            End While


            Using localDb As New UTS_Core.Database.DbExecutor(UTS_Core.UTSModule.UtsDb.LocalDbType, UTS_Core.UTSModule.UtsDb.LocalConnString) '连接本地字符串
                localDb.Open()
                localDb.BeginTransaction()
                Try
                    _jsonFile.ReadFile(localDb, FilePath)
                Catch ex As Exception
                    ServiceLog.WriteErrorLog($"_jsonFile.ReadFile TaskName:{TaskName},ListenJsonFile Error:{ex.Message}")
                End Try
                localDb.CommitTransaction()
                localDb.Close()
            End Using
        End While
    End Sub


    Public Overrides Sub Start()
        ServiceLog.WriteInfoLog($"FileListen Befor StartCallback")

        TaskStatus = ServiceTaskStatusEnum.Start

        If _syncThread IsNot Nothing AndAlso _syncThread.IsAlive Then
            ServiceLog.WriteInfoLog($"FileListenThread IsAlive!")
            Return
        End If

        _syncThread = New Thread(AddressOf StartCallback)
        _syncThread.IsBackground = True
        _syncThread.Start()

        ServiceLog.WriteInfoLog($"FileListen After StartCallback")
    End Sub


    Public Overrides Sub [Stop]()
        ServiceLog.WriteInfoLog($"FileListen Befor Stop!")
        TaskStatus = ServiceTaskStatusEnum.Stop

        Dim lastTime As DateTime = Now
        While _syncThread IsNot Nothing AndAlso _syncThread.IsAlive
            If (Now - lastTime).TotalMilliseconds > 10000 Then
                _syncThread.Abort()
            End If

            Thread.Sleep(10)
        End While

        ServiceLog.WriteInfoLog($"FileListen Stop!")
    End Sub


    Public Overrides Sub Restart()
        ServiceLog.WriteInfoLog($"FileListen Befor Restart!")
        If _syncThread IsNot Nothing AndAlso _syncThread.IsAlive Then
            [Stop]()

        End If

        Start()
        ServiceLog.WriteInfoLog($"FileListen Restart!")
    End Sub


    Public Overrides Sub SetParams(params As Dictionary(Of String, String))
        Dim tmpStatus As ServiceTaskStatusEnum
        Dim tmpInterval As Integer
        Dim tmpPath As String = String.Empty

        '将转换后的数据填充至临时缓存,一遍设置失败时可以保留上一次数据
        For Each param As KeyValuePair(Of String, String) In params
            Select Case param.Key
                Case "Interval"
                    If Integer.TryParse(param.Value, tmpInterval) = False Then
                        Throw New Exception($"Error Interval :{param.Value}")
                    End If
                Case "Path"
                    tmpPath = param.Value
                Case "Status", "Type", "Name" '不处理的字段
            End Select
        Next

        TaskStatus = tmpStatus
        Interval = tmpInterval
        FilePath = tmpPath
    End Sub


    Public Overrides Function GetParams() As Dictionary(Of String, String)
        Dim params As New Dictionary(Of String, String) From {
            {"Type", TaskType.ToString()},
            {"Name", TaskName},
            {"Status", TaskStatus.ToString()},
            {"Interval", Interval.ToString()},
            {"Path", FilePath}
        }
        Return params
    End Function


    Public Property Interval() As Integer

    Public Property FilePath() As String

    Private _syncThread As Thread
End Class
