Namespace UTSModule.Test.Command.ComPortCommand
    Public Class ConfigComAliasExecutor
        Inherits TestCommandExecutor

        Private ReadOnly _portName As String

        Private ReadOnly _portAlias As String

        Private ReadOnly _portList As List(Of ComPort)

        Public Sub New(command As TestCommand, portList As List(Of ComPort))
            MyBase.New(command)

            _portName = command.Parameter(0)
            _portAlias = command.Parameter(1)

            _portList = portList
        End Sub


        Public Overrides Function Execute() As TestCommandReturn
            '从历史使用串口中查询
            For Each comPort As ComPort In _portList
                If comPort.NameEqual(_portName) Then
                    comPort.PortAlias = _portAlias

                    CommandReturn.ExecuteResultTipString = $"串口重命名成功"
                    CommandReturn.ExecuteResult = True

                    Return CommandReturn
                Else
                    '如果已设置的串口别名与新的别名重名，则清除那个串口的别名
                    If comPort.AliasEqual(_portAlias) Then
                        comPort.PortAlias = String.Empty
                    End If
                End If
            Next

            '从当前设备上串口中查询
            Dim names As String() = IO.Ports.SerialPort.GetPortNames()
            For Each name As String In names
                If String.Compare(_portName, name, True) = 0 Then
                    _portList.Add(New ComPort(_portName, _portAlias))

                    CommandReturn.ExecuteResultTipString = $"串口重命名成功"
                    CommandReturn.ExecuteResult = True

                    Return CommandReturn
                End If
            Next

            '未查询到历史使用的串口
            CommandReturn.ExecuteResultTipString = $"串口重命名失败,未查询到串口[{_portName}]存在"
            CommandReturn.ExecuteResult = False
            Return CommandReturn
        End Function

    End Class

End Namespace