#import "../utils.typ": get-ctx, set-ctx
#import "../../consts.typ": *
#import "../../cetz.typ": draw

#let render-start(grp) = get-ctx(ctx => {
  let grp = grp
  ctx.y -= Y-SPACE
  let m = measure(
    box(
      grp.name,
      inset: (
        left: 5pt,
        right: 5pt,
        top: 3pt,
        bottom: 3pt
      ),
    )
  )
  ctx.groups = ctx.groups.map(g => {
    if g.at(1).min-i == grp.min-i { g.at(2) += 1 }
    if g.at(1).max-i == grp.max-i { g.at(3) += 1 }
    g
  })
  if grp.grp-type == "alt" {
    grp.insert("elses", ())
  }
  ctx.groups.push((ctx.y, grp, 0, 0))
  ctx.y -= m.height / 1pt

  set-ctx(c => {
    c.y = ctx.y
    c.groups = ctx.groups
    return c
  })
})


#let draw-group(x0, x1, y0, y1, group) = {
  let name = text(group.name, weight: "bold")
  let m = measure(box(name))
  let w = m.width / 1pt + 15
  let h = m.height / 1pt + 6
  draw.rect(
    (x0, y0),
    (x1, y1)
  )
  draw.merge-path(
    fill: COL-GRP-NAME,
    close: true,
    {
      draw.line(
        (x0, y0),
        (x0 + w, y0),
        (x0 + w, y0 - h / 2),
        (x0 + w - 5, y0 - h),
        (x0, y0 - h)
      )
    }
  )
  draw.content(
    (x0, y0),
    name,
    anchor: "north-west",
    padding: (left: 5pt, right: 10pt, top: 3pt, bottom: 3pt)
  )

  if group.desc != none {
    draw.content(
      (x0 + w, y0),
      text([\[#group.desc\]], weight: "bold", size: .8em),
      anchor: "north-west",
      padding: 3pt
    )
  }
}

#let draw-else(x0, x1, y, elmt) = {
  draw.line(
    (x0, y),
    (x1, y),
    stroke: (dash: (2pt, 1pt), thickness: .5pt)
  )
  draw.content(
    (x0, y),
    text([\[#elmt.desc\]], weight: "bold", size: .8em),
    anchor: "north-west",
    padding: 3pt
  )
}

#let render-end(group) = get-ctx(ctx => {
  ctx.y -= Y-SPACE
  let (start-y, group, start-lvl, end-lvl) = ctx.groups.pop()
  let x0 = ctx.x-pos.at(group.min-i) - start-lvl * 10 - 20
  let x1 = ctx.x-pos.at(group.max-i) + end-lvl * 10 + 20
  
  draw-group(x0, x1, start-y, ctx.y, group)

  if group.grp-type == "alt" {
    for (else-y, else-elmt) in group.elses {
      draw-else(x0, x1, else-y, else-elmt)
    }
  }

  set-ctx(c => {
    c.y = ctx.y
    c.groups = ctx.groups
    return c
  })
})

#let render-else(else_) = set-ctx(ctx => {
  ctx.y -= Y-SPACE
  let m = measure(text([\[#else_.desc\]], weight: "bold", size: .8em))
  ctx.groups.last().at(1).elses.push((
    ctx.y, else_
  ))
  ctx.y -= m.height / 1pt
  return ctx
})