use bone_types::Point2;

#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Aabb2 {
    min: Point2,
    max: Point2,
}

impl Aabb2 {
    #[must_use]
    pub fn from_corners(a: Point2, b: Point2) -> Self {
        let (ax, ay) = a.coords_mm();
        let (bx, by) = b.coords_mm();
        Self {
            min: Point2::from_mm(ax.min(bx), ay.min(by)),
            max: Point2::from_mm(ax.max(bx), ay.max(by)),
        }
    }

    #[must_use]
    pub fn min(self) -> Point2 {
        self.min
    }

    #[must_use]
    pub fn max(self) -> Point2 {
        self.max
    }

    #[must_use]
    pub fn extend_point(self, p: Point2) -> Self {
        let (px, py) = p.coords_mm();
        let (mnx, mny) = self.min.coords_mm();
        let (mxx, mxy) = self.max.coords_mm();
        Self {
            min: Point2::from_mm(mnx.min(px), mny.min(py)),
            max: Point2::from_mm(mxx.max(px), mxy.max(py)),
        }
    }
}

impl core::fmt::Display for Aabb2 {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let (mnx, mny) = self.min.coords_mm();
        let (mxx, mxy) = self.max.coords_mm();
        write!(
            f,
            "aabb2{{ min=({mnx} mm, {mny} mm), max=({mxx} mm, {mxy} mm) }}"
        )
    }
}
