// Content formats: how a source file becomes HTML.
//
// A page is always templated first. What happens next depends on the format
// registered for its extension: Markdown is converted, HTML is passed through.
// Adding a format (AsciiDoc, MDX, CSV-to-table, a custom DSL) means registering
// one `ContentFormat`; neither the build pipeline nor the CLI changes.

///|
/// One page format.
///
/// `render` receives the templated body and returns HTML. Formats that are
/// already HTML use the identity function; Markdown converts.
pub struct ContentFormat {
  name : String
  exts : Array[String]
  render : (StringView) -> String
}

///|
/// A registry of page formats, keyed by extension.
pub struct ContentRegistry {
  formats : Array[ContentFormat]
}

///|
/// Create a page format.
///
/// `exts` are lowercase extensions without a dot. `render` receives the already
/// templated body, so a format never needs to know about the template engine.
pub fn ContentFormat::new(
  name : String,
  exts : Array[String],
  render : (StringView) -> String,
) -> ContentFormat {
  ContentFormat::{ name, exts, render, }
}

///|
/// Create an empty registry.
pub fn ContentRegistry::new() -> ContentRegistry {
  ContentRegistry::{ formats: [], }
}

///|
/// Create a registry with Markdown and HTML registered.
///
/// `.jinja`, `.j2` and `.liquid` are HTML pages whose template dialect is picked
/// by the engine registry, so they share the identity transform.
pub fn ContentRegistry::builtin() -> ContentRegistry {
  let registry = ContentRegistry::new()
  registry.register(
    ContentFormat::new(
      "markdown",
      ["md", "markdown"],
      @markdown.render_markdown,
    ),
  )
  registry.register(
    ContentFormat::new("html", ["html", "htm", "jinja", "j2", "liquid"], fn(
      html : StringView,
    ) -> String {
      html.to_owned()
    }),
  )
  registry
}

///|
/// Register a format. Later formats win for a shared extension.
pub fn ContentRegistry::register(
  self : ContentRegistry,
  format : ContentFormat,
) -> Unit {
  self.formats.push(format)
}

///|
/// The format handling `path`, if any.
pub fn ContentRegistry::find(
  self : ContentRegistry,
  path : StringView,
) -> ContentFormat? {
  let ext = @formats.format_of_path(path)
  for i = self.formats.length() - 1; i >= 0; i = i - 1 {
    if self.formats[i].exts.contains(ext) {
      return Some(self.formats[i])
    }
  }
  None
}

///|
/// Transform a templated body into HTML using the format for `path`.
///
/// Unknown extensions are emitted as-is, so a page may use any extension as
/// long as it is listed in `pageExtensions`.
pub fn ContentRegistry::render(
  self : ContentRegistry,
  path : StringView,
  html : String,
) -> String {
  match self.find(path) {
    Some(format) => (format.render)(html)
    None => html
  }
}

///|
/// Every extension handled by the registry, in registration order.
pub fn ContentRegistry::extensions(self : ContentRegistry) -> Array[String] {
  let result : Array[String] = []
  for format in self.formats {
    for ext in format.exts {
      if !result.contains(ext) {
        result.push(ext)
      }
    }
  }
  result
}

///|
/// Names of the registered formats, for diagnostics.
pub fn ContentRegistry::names(self : ContentRegistry) -> Array[String] {
  self.formats.map(fn(format) { format.name })
}

///|
/// Render a page body: template first, then the format transform.
///
/// Templating runs before Markdown so that a `{% for %}` loop can generate list
/// items or table rows that Markdown then parses as real blocks.
pub fn render_body(
  body : String,
  src : StringView,
  ctx : Json,
  env : @engine.TemplateEnv,
  registry : ContentRegistry,
) -> String {
  let templated = @engine.render_source_of(body, src, ctx, env)
  registry.render(src, templated)
}