
Namespace UTSModule.Test.Command.ConverterCommand
    Public Class GetUTF8StringExecutor
        Inherits TestCommandExecutor

        Private ReadOnly _hexString As String
        Private ReadOnly _startIndex As Integer
        Private ReadOnly _length As Integer
        Sub New(command As TestCommand)
            MyBase.New(command)

            _hexString = command.Parameter(0)
            _startIndex = CInt(command.Parameter(1))
            _length = CInt(command.Parameter(2))
        End Sub

        Public Overrides Function Execute() As TestCommandReturn
            Dim tmp As String() = _hexString.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
            If tmp.Length = 0 Then
                CommandReturn.RecordValue = String.Empty
                CommandReturn.ExecuteResultTipString = $"转换结果长度为0"
                CommandReturn.ExecuteResult = True
                Return CommandReturn
            End If

            Dim bytes(tmp.Length - 1) As Byte
            Try
                For j As Integer = 0 To tmp.Length - 1
                    bytes(j) = CByte($"&H{tmp(j)}")
                Next
            Catch ex As Exception
                CommandReturn.RecordValue = String.Empty
                CommandReturn.ExecuteResultTipString = $"转换失败,数组数据转换为Hex数据失败。"
                CommandReturn.ExecuteResult = False
                Return CommandReturn
            End Try

            If _startIndex + _length > bytes.Length Then
                CommandReturn.RecordValue = String.Empty
                CommandReturn.ExecuteResultTipString = $"转换失败,目标长度超过原数据长度"
                CommandReturn.ExecuteResult = False
                Return CommandReturn
            End If

            CommandReturn.RecordValue = Text.Encoding.UTF8.GetString(bytes, _startIndex, _length).Replace(vbNullChar, "")
            CommandReturn.ExecuteResultTipString = $"获取的字符串结果为：{_hexString}"
            CommandReturn.ExecuteResult = True

            Return CommandReturn
        End Function
    End Class
End Namespace

