package com.zehong.system.udp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lenovo
 * @date 2025/8/4
 * @description TODO
 */
@Component
public class UdpCommandSender {
    private static final Logger log = LoggerFactory.getLogger(UdpCommandSender.class);

    @Value("${robot.arm.udp.ip}")
    private String robotArmIp;

    @Value("${robot.arm.udp.port}")
    private int robotArmPort;

    private DatagramSocket socket;
    private InetAddress address;

    private final ReentrantLock lock = new ReentrantLock();
    @PostConstruct
    public void init() {
        try {
            socket = new DatagramSocket();
            address = InetAddress.getByName(robotArmIp);
            log.info("UDP命令发送器初始化成功，目标地址: {}:{}", robotArmIp, robotArmPort);
        } catch (Exception e) {
            log.error("UDP命令发送器初始化失败", e);
        }
    }

    /**
     * 发送指令到指定地址
     */
    public void sendCommand(SocketAddress address, String message) {
        if (socket == null || address == null) {
            log.error("UDP命令发送器未初始化或地址无效");
            return;
        }

        lock.lock();
        try {
            byte[] buffer = message.getBytes(StandardCharsets.UTF_8);
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address);
            socket.send(packet);
            log.info("已发送UDP指令到 {}: {}", address, message);
        } catch (IOException e) {
            log.error("发送UDP指令失败: {}", message, e);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 发送带指令ID的命令
     */
    public void sendCommandWithId(SocketAddress address, String command) {
        sendCommand(address, command);
    }

    public void sendCommandThrowError(String message) throws IOException {
        if(socket == null || address == null){
            throw new RuntimeException("UDP命令发送器未初始化，无法发送消息");
        }
        byte[] buffer = message.getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, robotArmPort);
        socket.send(packet);
    }

    public void sendCommand(String message) {
        if (socket == null || address == null) {
            log.error("UDP命令发送器未初始化，无法发送消息");
            return;
        }

        try {
            byte[] buffer = message.getBytes(StandardCharsets.UTF_8);
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, robotArmPort);
            socket.send(packet);
            log.info("已发送UDP指令: {}", message);
        } catch (IOException e) {
            log.error("发送UDP指令失败: {}", message, e);
        }
    }

    @PreDestroy
    public void cleanup() {
        if (socket != null && !socket.isClosed()) {
            socket.close();
            log.info("UDP命令发送器已关闭");
        }
    }
}
