///|
/// Shared state passed to every plugin: the numeric precision plus a cache
/// that lives for the whole run.
#derive(Debug)
pub struct Context {
  /// decimal places for numeric attribute values and path data
  precision : Int32
  /// current plugin parameter object; set by the pipeline before each run
  mut params : Json
  /// path data convertPathData has already left unchanged in this run,
  /// with the element style it was optimized for
  optimized_paths : Map[String, Int32]
  /// convex hulls of each subpath, per path data string, for mergePaths'
  /// intersection test (paths are compared against both neighbours on
  /// every pass, so this saves most of the parsing and hull building)
  path_hulls : Map[String, Array[Array[(Double, Double)]]]
}

///|
pub extend Context with Debug::{to_repr}

///|
/// A fresh context; create one per `optimize` run.
pub fn Context::new(precision~ : Int32 = 3) -> Context {
  {
    precision,
    params: Json::object(Map([])),
    optimized_paths: Map([]),
    path_hulls: Map([]),
  }
}

///|
/// A plugin transforms the document in place and reports whether it changed
/// anything, which drives multipass optimization. Built-in plugins and the
/// ones a caller passes in `Config::custom` follow the same rules:
///
/// - only remove or rewrite what a renderer cannot observe at
///   `Context::precision`;
/// - return `true` exactly when the document changed, otherwise every run
///   takes the maximum of 10 passes;
/// - run on any document, in any position of the pipeline, without raising;
/// - read parameters with `Context::param_bool`, `param_int`, `param_string`
///   and `param_strings`, which see the object `Config::params` holds under
///   the plugin's `name`.
pub(all) struct Plugin {
  name : String
  description : String
  run : (@xml.Document, Context) -> Bool
}

///|
pub impl Debug for Plugin with fn to_repr(self) {
  Repr(self.name)
}

///|
pub extend Plugin with Debug::{to_repr}

///|
/// Remove every child node for which `pred` holds; returns true if any was removed.
fn remove_children(e : @xml.Element, pred : (@xml.Node) -> Bool) -> Bool {
  let before = e.children.length()
  e.children.retain(c => !pred(c))
  e.children.length() != before
}

///|
fn remove_top_level(doc : @xml.Document, pred : (@xml.Node) -> Bool) -> Bool {
  let before = doc.children.length()
  doc.children.retain(c => !pred(c))
  doc.children.length() != before
}

///|
/// Remove elements matching `pred` anywhere below the root. Children are
/// visited before their parent, so a container emptied by the predicate can
/// be removed in the same pass.
fn remove_elements(
  doc : @xml.Document,
  pred : (@xml.Element, @xml.Element?) -> Bool,
) -> Bool {
  let mut changed = false
  fn walk(e : @xml.Element) {
    let mut has_elements = false
    for c in e.children {
      if c is Element(x) {
        has_elements = true
        walk(x)
      }
    }
    if has_elements {
      let before = e.children.length()
      let parent = Some(e)
      e.children.retain(c => !(c is Element(x) && pred(x, parent)))
      if e.children.length() != before {
        changed = true
      }
    }
  }
  if doc.root() is Some(root) {
    walk(root)
  }
  changed
}

///|
/// Remove attributes for which `pred` holds; returns true if any was removed.
fn remove_attrs(e : @xml.Element, pred : (String, String) -> Bool) -> Bool {
  let before = e.attrs.length()
  e.attrs.retain((k, v) => !pred(k, v))
  e.attrs.length() != before
}

///|
/// Split a numeric attribute value into number and unit ("12.5px" -> (12.5, "px")).
fn split_unit(s : String) -> (Double, String)? {
  let t = s.trim()
  let mut end = t.length()
  while end > 0 &&
        (
          t.get_char(end - 1).unwrap().is_ascii_alphabetic() ||
          t.get_char(end - 1) == Some('%')
        ) {
    end -= 1
  }
  if end == 0 {
    return None
  }
  guard @num.parse_number(t[:end].to_owned()) is Some(v) else { return None }
  Some((v, t[end:].to_owned()))
}

///|
/// Elements that are containers for other content.
let container_elements : Set[String] = Set([
  "a", "defs", "foreignObject", "g", "marker", "mask", "missing-glyph", "pattern",
  "svg", "switch", "symbol", "text", "textPath", "tspan",
])

///|
/// Attributes whose value may reference an element: `url(#id)` in paint
/// servers and effects, `#id` in links, `id.event` in animation timing.
let reference_attrs : Set[String] = Set([
  "fill", "stroke", "filter", "clip-path", "mask", "marker", "marker-start", "marker-mid",
  "marker-end", "cursor", "color-profile", "begin", "end", "style",
])

///|
/// Collect every id referenced anywhere in the document: `href="#id"`,
/// `url(#id)` in attributes and `