import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import gnu.io.*;

public class LEDControllerTester implements SerialPortEventListener {
    private static final int BAUD_RATE = 9600;
    private static final int TIMEOUT = 2000;
    
    private SerialPort serialPort;
    private InputStream input;
    private OutputStream output;
    private BufferedReader reader;
    
    private String portName;
    
    public LEDControllerTester(String portName) {
        this.portName = portName;
    }
    
    public boolean connect() {
        try {
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
            
            if (portIdentifier.isCurrentlyOwned()) {
                System.err.println("串口 " + portName + " 已被占用");
                return false;
            }
            
            CommPort commPort = portIdentifier.open(this.getClass().getName(), TIMEOUT);
            
            if (commPort instanceof SerialPort) {
                serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(BAUD_RATE, 
                    SerialPort.DATABITS_8, 
                    SerialPort.STOPBITS_1, 
                    SerialPort.PARITY_NONE);
                
                serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
                serialPort.enableReceiveTimeout(TIMEOUT);
                
                input = serialPort.getInputStream();
                output = serialPort.getOutputStream();
                reader = new BufferedReader(new InputStreamReader(input));
                
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
                
                System.out.println("已连接到 " + portName + "，波特率 " + BAUD_RATE);
                return true;
                
            } else {
                System.err.println(portName + " 不是串口");
                return false;
            }
            
        } catch (Exception e) {
            System.err.println("连接失败: " + e.getMessage());
            return false;
        }
    }
    
    public synchronized void sendCommand(String command) {
        System.out.println("\n发送: " + command);
        
        try {
            String cmd = command + "\r\n";
            output.write(cmd.getBytes());
            output.flush();
            
            // 等待响应
            Thread.sleep(500);
            
            // 读取响应
            StringBuilder response = new StringBuilder();
            while (input.available() > 0) {
                byte[] buffer = new byte[input.available()];
                int bytesRead = input.read(buffer);
                if (bytesRead > 0) {
                    response.append(new String(buffer, 0, bytesRead));
                }
            }
            
            if (response.length() > 0) {
                String[] lines = response.toString().split("\r\n");
                for (String line : lines) {
                    if (!line.trim().isEmpty()) {
                        System.out.println("收到: " + line.trim());
                    }
                }
            } else {
                System.out.println("无响应");
            }
            
        } catch (Exception e) {
            System.err.println("发送命令失败: " + e.getMessage());
        }
    }
    
    public void testAllCommands() {
        System.out.println("=== LED控制器测试开始 ===\n");
        
        // 1. 帮助命令
        System.out.println("1. 测试 HELP 命令:");
        sendCommand("HELP");
        
        // 2. 模式切换
        System.out.println("\n2. 测试模式切换:");
        String[] modes = {"WHITE", "WARM", "NATURAL"};
        for (String mode : modes) {
            sendCommand(mode);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        
        // 3. 亮度调节
        System.out.println("\n3. 测试亮度调节:");
        for (int i = 0; i < 3; i++) {
            sendCommand("HIGH");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        for (int i = 0; i < 3; i++) {
            sendCommand("LOW");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        
        // 4. GEAR命令
        System.out.println("\n4. 测试 GEAR 命令:");
        int[] gears = {0, 32, 64, 96, 128};
        for (int gear : gears) {
            sendCommand("GEAR " + gear);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        
        // 5. 状态查询
        System.out.println("\n5. 测试 STATUS 命令:");
        sendCommand("STATUS");
        
        // 6. 关闭
        System.out.println("\n6. 测试 OFF 命令:");
        sendCommand("OFF");
        
        System.out.println("\n=== 测试完成 ===");
    }
    
    public void interactiveMode() {
        System.out.println("\n进入交互模式 (输入 quit 退出)\n");
        
        Scanner scanner = new Scanner(System.in);
        
        while (true) {
            System.out.print("输入命令: ");
            String command = scanner.nextLine().trim();
            
            if (command.equalsIgnoreCase("quit")) {
                break;
            }
            
            if (!command.isEmpty()) {
                sendCommand(command);
            }
        }
        
        scanner.close();
    }
    
    public void disconnect() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
            System.out.println("串口已关闭");
        }
    }
    
    @Override
    public void serialEvent(SerialPortEvent event) {
        // 可以在这里处理异步接收的数据
        if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            // 数据可用时的处理
        }
    }
    
    public static void main(String[] args) {
        String portName = "COM3"; // 默认值
        boolean interactive = false;
        
        // 解析命令行参数
        for (int i = 0; i < args.length; i++) {
            switch (args[i]) {
                case "--port":
                    if (i + 1 < args.length) {
                        portName = args[++i];
                    }
                    break;
                case "--interactive":
                    interactive = true;
                    break;
                case "--help":
                    printHelp();
                    return;
            }
        }
        
        LEDControllerTester tester = new LEDControllerTester(portName);
        
        if (tester.connect()) {
            try {
                if (interactive) {
                    tester.interactiveMode();
                } else {
                    tester.testAllCommands();
                }
            } finally {
                tester.disconnect();
            }
        }
    }
    
    private static void printHelp() {
        System.out.println("LED控制器串口测试工具");
        System.out.println();
        System.out.println("用法: java LEDControllerTester [选项]");
        System.out.println();
        System.out.println("选项:");
        System.out.println("  --port <端口>     串口端口 (默认: COM3)");
        System.out.println("  --interactive     交互模式");
        System.out.println("  --help            显示帮助信息");
        System.out.println();
        System.out.println("示例:");
        System.out.println("  java LEDControllerTester --port COM3");
        System.out.println("  java LEDControllerTester --port /dev/ttyUSB0 --interactive");
    }
}