package com.zehong.system.udp;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lenovo
 * @date 2025/8/5
 * @description TODO
 */
public class RobotArmMessageParser {
    private static final Pattern STATUS_PATTERN = Pattern.compile(
            "PPP (\\w+) (\\S+)(?: (\\d+),(\\d+),(\\d+),(\\d+),)?"
    );

    public static RobotArmStatus parseMessage(String message) {
        Matcher matcher = STATUS_PATTERN.matcher(message);
        if (matcher.find()) {
            String statusCode = matcher.group(1);
            String statusText = matcher.group(2);
            String x = matcher.group(3);
            String y = matcher.group(4);
            String z = matcher.group(5);
            String r = matcher.group(6);

            return new RobotArmStatus(statusCode, statusText,
                    parseCoord(x), parseCoord(y),
                    parseCoord(z), parseCoord(r));
        }
        return null;
    }

    private static Integer parseCoord(String coord) {
        if (coord == null || coord.isEmpty()) return null;
        try {
            return Integer.parseInt(coord);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    public static class RobotArmStatus {
        private final String code;
        private final String text;
        private final Integer x;
        private final Integer y;
        private final Integer z;
        private final Integer r;

        public RobotArmStatus(String code, String text,
                              Integer x, Integer y, Integer z, Integer r) {
            this.code = code;
            this.text = text;
            this.x = x;
            this.y = y;
            this.z = z;
            this.r = r;
        }

        public boolean isBusy() {
            return "BUSY".equals(code);
        }

        public boolean isOk() {
            return "OK".equals(code);
        }

        public boolean isComplete() {
            return isOk() && "完成".equals(text);
        }

        public boolean isFullyIdle() {
            return isComplete() && x == 0 && y == 0 && z == 0 && r == 0;
        }

        // Getters
        public String getCode() { return code; }
        public String getText() { return text; }
        public Integer getX() { return x; }
        public Integer getY() { return y; }
        public Integer getZ() { return z; }
        public Integer getR() { return r; }
    }
}
