#import "@preview/cetz:0.4.2"

#let bitFieldField(name, color, total) = {
  (name: name, color: color, total: total)
}

#let bitFieldGreen = rgb("#8fff57")
#let bitFieldYellow = rgb("#ffe057")
#let bitFieldBlue = rgb("#57a5ff")
#let bitFieldRed = rgb("#ff5757")

#let bitField(fields: (), BitHeight: 0.5, BitWidth: 0.25) = {
  cetz.canvas({
    import cetz.draw : *
    let pos = 0;

    let total = 0;

    for f in fields {
      total += f.at("total")
    }

    for f in fields {
      content(((pos + 0.5)*BitWidth, -0.1), raw(str(total - pos - 1)), angle: 90deg, anchor: "east")

      for i in range(f.at("total")) {
        rect(((pos + i)*BitWidth, 0), ((pos+i+1)*BitWidth, BitHeight), fill: f.at("color", default: bitFieldBlue))
        content(((pos+i+0.5)*BitWidth, BitHeight*0.5), raw("0"))
      }

      content(((pos*BitWidth + f.at("total")*BitWidth*0.5), BitHeight + 0.2), f.at("name"), anchor: f.at("anchor", default: "mid"))

      pos += f.at("total")

      content(((pos - 0.5)*BitWidth, -0.1), raw(str(total - pos)), angle: 90deg, anchor: "east")

    }
  })
}

