///|
#derive(Debug, Eq)
pub(all) struct Question {
  options : Int32
  max_marks : Int32
}

///|
pub struct Template {
  title : String
  questions : ArrayView[Question]
  signature : UInt32
}

///|
const PAGE_WIDTH : Int32 = 840

///|
const PAGE_HEIGHT : Int32 = 1188

///|
const BUBBLE_RADIUS : Int32 = 10

///|
const MARKER_HALF : Int32 = 15

///|
const CODE_BITS : Int32 = 20

///|
pub fn Template::new(
  title : String,
  questions : Array[Question],
) -> Template raise MarkError {
  if title.length() < 1 || title.length() > 80 {
    raise Invalid("template title must be 1 to 80 code units")
  }
  for character in title {
    if character.to_int() < 32 || character.to_int() == 127 {
      raise Invalid("template title contains a control character")
    }
  }
  if questions.is_empty() || questions.length() > 60 {
    raise Invalid("template must contain 1 to 60 questions")
  }
  let mut signature = 2166136261U
  for character in title {
    signature = (signature ^ character.to_int().reinterpret_as_uint()) *
      16777619U
  }
  for question in questions {
    if question.options < 2 ||
      question.options > 8 ||
      question.max_marks < 1 ||
      question.max_marks > question.options {
      raise Invalid(
        "each question needs 2 to 8 options and a valid selection limit",
      )
    }
    let code = question.options * 16 + question.max_marks
    signature = (signature ^ code.reinterpret_as_uint()) * 16777619U
  }
  signature = signature & ((1U << CODE_BITS) - 1U)
  // ponytail: a short layout code catches wrong templates in normal use.
  // Compare the full template separately where identity must be exact.
  { title, questions: questions.copy()[:], signature, }
}

///|
pub fn Template::uniform(
  title : String,
  question_count : Int32,
  options : Int32,
  max_marks : Int32,
) -> Template raise MarkError {
  if question_count < 1 || question_count > 60 {
    raise Invalid("question count must be 1 to 60")
  }
  Template::new(title, Array::make(question_count, { options, max_marks, }))
}

///|
#derive(Debug, Eq)
pub(all) struct Point {
  x : Double
  y : Double
}

///|
fn point(x : Int32, y : Int32) -> Point {
  { x: x.to_double(), y: y.to_double(), }
}

///|
fn template_markers() -> Array[Point] {
  [point(51, 51), point(788, 51), point(788, 1136), point(51, 1136)]
}

///|
fn pilot_x(index : Int32) -> Int32 {
  130 + index * 25
}

///|
const PILOT_Y : Int32 = 108

///|
fn pilot_bit(template : Template, index : Int32) -> Bool {
  if index < 3 {
    [true, false, true][index]
  } else if index == CODE_BITS + 3 {
    true
  } else {
    ((template.signature >> (index - 3)) & 1U) != 0U
  }
}

///|
fn Template::row_position(self : Template, index : Int32) -> (Int32, Int32) {
  let split = (self.questions.length() + 1) / 2
  if index < split {
    (78, 168 + index * 30)
  } else {
    (464, 168 + (index - split) * 30)
  }
}

///|
pub fn Template::bubble(
  self : Template,
  question : Int32,
  option : Int32,
) -> Point raise MarkError {
  if question < 0 ||
    question >= self.questions.length() ||
    option < 0 ||
    option >= self.questions[question].options {
    raise Invalid("bubble index is outside the template")
  }
  self.bubble_position(question, option)
}

///|
fn Template::bubble_position(
  self : Template,
  question : Int32,
  option : Int32,
) -> Point {
  let (left, y) = self.row_position(question)
  point(left + 57 + option * 31, y)
}

///|
fn option_name(index : Int32) -> String {
  ["A", "B", "C", "D", "E", "F", "G", "H"][index]
}

///|
fn xml_escape(value : String) -> String {
  let out = StringBuilder()
  for character in value {
    match character {
      '&' => out.write_string("&")
      '<' => out.write_string("<")
      '>' => out.write_string(">")
      '"' => out.write_string(""")
      _ => out.write_char(character)
    }
  }
  out.to_string()
}

///|
pub fn Template::svg(self : Template) -> String {
  self.svg_page(None)
}

///|
pub fn Template::numbered_svg(
  self : Template,
  serial : Int32,
) -> String raise MarkError {
  assert_serial(serial)
  self.svg_page(Some(serial))
}

///|
fn Template::svg_page(self : Template, serial : Int32?) -> String {
  let out = StringBuilder()
  out.write_string(
    "\n",
  )
  out.write_string("\n")
  out.write_string("\n")
  for marker in template_markers() {
    let x = marker.x.to_int() - MARKER_HALF
    let y = marker.y.to_int() - MARKER_HALF
    out.write_string(
      "\n",
    )
  }
  let title = xml_escape(self.title)
  out.write_string(
    "\{title}\n",
  )
  for bit in 0..<(CODE_BITS + 4) {
    if pilot_bit(self, bit) {
      let x = pilot_x(bit) - 5
      out.write_string(
        "\n",
      )
    }
  }
  out.write_string(
    "Fill the circle. Keep the page and four corner squares visible.\n",
  )
  for index in 0..\{number}\n",
    )
    for option in 0..\n",
      )
      let letter = option_name(option)
      out.write_string(
        "\{letter}\n",
      )
    }
  }
  if serial is Some(value) {
    append_serial_svg(out, value)
  }
  out.write_string("\n\n")
  out.to_string()
}