// EXACT layer (M3): a trimmed 2D curve — a base NurbsCurve2 restricted to a set
// of disjoint parameter intervals (the kept portions). Trim loops in parameter
// space are the building blocks of trimmed surfaces and 2D boolean regions.
// Reference: curvo/src/trim/, curvo/src/curve/trimmed_curve.rs.

///|
pub(all) struct TrimmedCurve2 {
  curve : NurbsCurve2
  intervals : Array[(Double, Double)]
}

///|
/// Build a trimmed curve from sorted, disjoint intervals within the curve domain.
/// Intervals are validated (u0 < u1, in domain, non-overlapping) and sorted.
pub fn TrimmedCurve2::new(
  curve : NurbsCurve2,
  intervals : Array[(Double, Double)],
) -> TrimmedCurve2? {
  let n = curve.bspline.ctrlpts.length() - 1
  let knots = curve.bspline.knots.knots
  let d0 = knots[curve.bspline.degree]
  let d1 = knots[n + 1]
  // Sort by start parameter (insertion sort; interval counts are small).
  let sorted : Array[(Double, Double)] = []
  for i = 0; i < intervals.length(); i = i + 1 {
    let (a, b) = intervals[i]
    if a >= b || a < d0 || b > d1 {
      return None
    }
    let mut j = sorted.length()
    while j > 0 {
      let (pa, _) = sorted[j - 1]
      if pa <= a {
        break
      }
      j = j - 1
    }
    sorted.insert(j, (a, b))
  }
  // Check disjoint (allow touching endpoints).
  for i = 1; i < sorted.length(); i = i + 1 {
    let (_, prev_b) = sorted[i - 1]
    let (a, _) = sorted[i]
    if a < prev_b {
      return None
    }
  }
  Some({ curve, intervals: sorted })
}

///|
pub fn TrimmedCurve2::contains(self : TrimmedCurve2, u : Double) -> Bool {
  for i = 0; i < self.intervals.length(); i = i + 1 {
    let (a, b) = self.intervals[i]
    if u >= a && u <= b {
      return true
    }
  }
  false
}

///|
/// Evaluate at `u` only if it lies in a kept interval; otherwise None.
pub fn TrimmedCurve2::point_at(self : TrimmedCurve2, u : Double) -> @f64.DVec2? {
  if !self.contains(u) {
    return None
  }
  self.curve.point_at(u)
}

///|
/// Flatten each kept interval into a polyline of `samples` segments. Returns one
/// polyline per interval (the input to 2D boolean / CDT pipelines).
pub fn TrimmedCurve2::flatten(
  self : TrimmedCurve2,
  samples? : Int = 16,
) -> Array[Array[@f64.DVec2]] {
  let out : Array[Array[@f64.DVec2]] = []
  for k = 0; k < self.intervals.length(); k = k + 1 {
    let (a, b) = self.intervals[k]
    let poly : Array[@f64.DVec2] = []
    for i = 0; i <= samples; i = i + 1 {
      let u = a + (b - a) * (i.to_double() / samples.to_double())
      match self.curve.point_at(u) {
        None => ()
        Some(p) => poly.push(p)
      }
    }
    out.push(poly)
  }
  out
}