package dev.bytevibe.hyperpoint;

import javafx.scene.paint.Color;

/**
 * 形状对象（矩形、圆、椭圆、直线）
 */
public class ShapeObject extends DrawableObject {
    public enum ShapeType {
        LINE, RECTANGLE, CIRCLE, ELLIPSE
    }

    private ShapeType shapeType;
    private String fillColor;      // 填充颜色
    private String strokeColor;    // 边框颜色
    private double strokeWidth;

    public ShapeObject(double x, double y, double width, double height, ShapeType shapeType) {
        super(x, y, width, height);
        this.shapeType = shapeType;
        this.fillColor = "FFFFFF";    // 白色填充
        this.strokeColor = "000000";  // 黑色边框
        this.strokeWidth = 2.0;
    }

    public ShapeType getShapeType() {
        return shapeType;
    }

    public void setShapeType(ShapeType shapeType) {
        this.shapeType = shapeType;
    }

    public String getFillColor() {
        return fillColor;
    }

    public void setFillColor(String fillColor) {
        this.fillColor = fillColor;
    }

    public Color getFillColorAsColor() {
        return Color.web("#" + fillColor);
    }

    public String getStrokeColor() {
        return strokeColor;
    }

    public void setStrokeColor(String strokeColor) {
        this.strokeColor = strokeColor;
    }

    public Color getStrokeColorAsColor() {
        return Color.web("#" + strokeColor);
    }

    public double getStrokeWidth() {
        return strokeWidth;
    }

    public void setStrokeWidth(double strokeWidth) {
        this.strokeWidth = strokeWidth;
    }

    @Override
    public boolean contains(double px, double py) {
        // 对于直线，使用更宽松的碰撞检测
        if (shapeType == ShapeType.LINE) {
            // 直线碰撞检测：点到线段的距离
            return distanceToLine(px, py) <= 5;
        }
        // 其他形状的简单矩形碰撞检测
        return px >= x && px <= x + width && py >= y && py <= y + height;
    }

    /**
     * 计算点到直线的距离
     */
    private double distanceToLine(double px, double py) {
        double x1 = this.x;
        double y1 = this.y;
        double x2 = this.x + this.width;
        double y2 = this.y + this.height;

        double A = py - y1;
        double B = px - x1;
        double C = y2 - y1;
        double D = x2 - x1;

        double dot = A * C + B * D;
        double lenSq = C * C + D * D;
        double param = (lenSq != 0) ? dot / lenSq : -1;

        double xx, yy;
        if (param < 0) {
            xx = x1;
            yy = y1;
        } else if (param > 1) {
            xx = x2;
            yy = y2;
        } else {
            xx = x1 + param * D;
            yy = y1 + param * C;
        }

        double dx = px - xx;
        double dy = py - yy;
        return Math.sqrt(dx * dx + dy * dy);
    }

    @Override
    public String getTypeName() {
        return "Shape_" + shapeType.name();
    }
}

