use bone_document::{ArcData, Sketch, SketchEntity, SketchEntityKind};

use crate::sketch_mode::Plane;

mod basic;
mod edge;
mod infer;
mod rect;

pub(super) use super::geometry::distance;

pub(super) fn count_kind(sketch: &Sketch, kind: SketchEntityKind) -> usize {
    sketch
        .entities()
        .iter()
        .filter(|(_, e)| e.kind() == kind)
        .count()
}

pub(super) fn fresh() -> Sketch {
    Sketch::new(Plane::Xy.basis())
}

pub(super) fn arc_sweep(sketch: &Sketch, arc: ArcData) -> f64 {
    let resolve = |id| match sketch.entities().get(id) {
        Some(SketchEntity::Point(p)) => p.at(),
        _ => panic!("point id {id:?} did not resolve"),
    };
    let (cx, cy) = resolve(arc.center()).coords_mm();
    let (sx, sy) = resolve(arc.start()).coords_mm();
    let (ex, ey) = resolve(arc.end()).coords_mm();
    let start_angle = (sy - cy).atan2(sx - cx);
    let end_angle = (ey - cy).atan2(ex - cx);
    (end_angle - start_angle).rem_euclid(std::f64::consts::TAU)
}

pub(super) fn only_arc(sketch: &Sketch) -> ArcData {
    let Some((_, SketchEntity::Arc(arc))) = sketch
        .entities()
        .iter()
        .find(|(_, e)| matches!(e, SketchEntity::Arc(_)))
    else {
        panic!("arc entity");
    };
    *arc
}
