// Template engines behind one registry.
//
// A `TemplateEngine` is a named backend with a set of file extensions. The
// environment holds every layout and include as source, plus the engines that
// render them. Adding an engine (Handlebars, Mustache, a custom DSL) means
// building one `TemplateEngine` value and calling `TemplateEnv::register`; the
// build pipeline does not change.

///|
/// Which engine is the default for pages and extensionless template names.
#derive(Eq)
pub enum EngineKind {
  MiniJinja
  Liquid
}

///|
/// Parse a `templateEngine` configuration value.
pub fn engine_kind(name : StringView) -> EngineKind {
  match name.to_lower() {
    "liquid" => Liquid
    _ => MiniJinja
  }
}

///|
/// One template backend.
///
/// `add_template` registers a layout or include under its name so that
/// `include` and `extends` can resolve it, `render_str` renders a page body
/// (inline source) and `render_named` renders a stored template with an
/// optional wrapped body injected as trusted HTML.
pub struct TemplateEngine {
  name : String
  exts : Array[String]
  add_template : (String, String) -> Unit
  render_str : (String, Json) -> String
  render_named : (String, String, Json, String?) -> String
}

///|
/// Build a custom engine.
///
/// `add_template` is called once per layout and include, `render_str` renders a
/// page body and `render_named` renders a stored template with an optional body.
/// Register the result with `TemplateEnv::register`; the extension decides which
/// files it owns (`exts`).
pub fn TemplateEngine::custom(
  name : String,
  exts : Array[String],
  add_template : (String, String) -> Unit,
  render_str : (String, Json) -> String,
  render_named : (String, String, Json, String?) -> String,
) -> TemplateEngine {
  TemplateEngine::{ name, exts, add_template, render_str, render_named, }
}

///|
/// A template environment: the registered engines plus every template source.
///
/// `kinds` remembers which engine each name belongs to, taken from the file it
/// was loaded from. Without it, `layout: base` had to guess: the name carries no
/// extension, so a `_layouts/base.liquid` was handed to the default engine and
/// came out as ``.
pub struct TemplateEnv {
  engines : Array[TemplateEngine]
  default_engine : EngineKind
  sources : Map[String, String]
  kinds : Map[String, String]
}

///|
/// Create an environment that renders with Jinja unless a file says otherwise.
pub fn TemplateEnv::new() -> TemplateEnv {
  TemplateEnv::with_engine(MiniJinja)
}

///|
/// Create an environment with an explicit default engine.
///
/// Both built-in engines are always registered, so `.liquid` files keep working
/// even when Jinja is the default.
pub fn TemplateEnv::with_engine(kind : EngineKind) -> TemplateEnv {
  let env = TemplateEnv::{
    engines: [],
    default_engine: kind,
    sources: Map([]),
    kinds: Map([]),
  }
  env.register(jinja_engine())
  env.register(liquid_engine())
  env
}

///|
/// Register an engine. Later engines win for a shared extension.
pub fn TemplateEnv::register(
  self : TemplateEnv,
  engine : TemplateEngine,
) -> Unit {
  self.engines.push(engine)
}

///|
/// Register a template under one name (`base`, `post`, `hello`).
///
/// Invalid syntax is swallowed: a typo in one layout reports at render time
/// instead of hiding every other page. The name carries no engine; use
/// `add_with` when the file it came from has an extension.
pub fn TemplateEnv::add(
  self : TemplateEnv,
  name : StringView,
  source : StringView,
) -> Unit {
  self.add_with(name, source, "")
}

///|
/// Register a template and remember the engine its file extension selects.
///
/// `ext` is the bare extension (`jinja`, `liquid`, `j2`); `""` leaves the name
/// on the default engine. Every engine still receives the source, because
/// `include` resolves inside the engine that is rendering — but the name itself
/// now resolves to the engine of the file it came from.
pub fn TemplateEnv::add_with(
  self : TemplateEnv,
  name : StringView,
  source : StringView,
  ext : StringView,
) -> Unit {
  let key = name.to_owned()
  self.sources.set(key, source.to_owned())
  if ext != "" {
    self.kinds.set(key, ext.to_owned())
  }
  for engine in self.engines {
    (engine.add_template)(key, source.to_owned())
  }
}

///|
/// Names of the registered engines, in registration order.
pub fn TemplateEnv::engine_names(self : TemplateEnv) -> Array[String] {
  let result : Array[String] = []
  for engine in self.engines {
    result.push(engine.name)
  }
  result
}

// Pick the engine for a template: the extension wins, the configured default
// covers pages and extensionless include names.

///|
fn engine_of(env : TemplateEnv, name : StringView) -> TemplateEngine {
  let ext = match env.kinds.get(name.to_owned()) {
    Some(kind) => kind
    None => @formats.format_of_path(name)
  }
  if ext != "" {
    for engine in env.engines {
      if engine.exts.contains(ext) {
        return engine
      }
    }
  }
  let wanted = match env.default_engine {
    MiniJinja => "jinja"
    Liquid => "liquid"
  }
  for engine in env.engines {
    if engine.name == wanted {
      return engine
    }
  }
  env.engines[0]
}

///|
/// Render an inline template source, used for page bodies.
pub fn render_source(
  source : StringView,
  ctx : Json,
  env : TemplateEnv,
) -> String {
  (engine_of(env, "").render_str)(source.to_owned(), ctx)
}

///|
/// Render an inline template source with the engine of `path`.
///
/// Page bodies use this: a `post.liquid` body is Liquid even when Jinja is the
/// default, and a `post.jinja` body stays Jinja even when `templateEngine` is
/// `liquid`. Extensions no engine owns (`.md`, `.html`) fall back to the default.
pub fn render_source_of(
  source : StringView,
  path : StringView,
  ctx : Json,
  env : TemplateEnv,
) -> String {
  (engine_of(env, path).render_str)(source.to_owned(), ctx)
}

///|
/// Render a registered template by name.
pub fn render_template(
  name : StringView,
  ctx : Json,
  env : TemplateEnv,
) -> String {
  match env.sources.get(name.to_owned()) {
    Some(source) =>
      (engine_of(env, name).render_named)(name.to_owned(), source, ctx, None)
    None => ""
  }
}

///|
/// Render a layout with `body` and `content` bound to trusted HTML.
pub fn render_layout(
  name : StringView,
  ctx : Json,
  body_html : StringView,
  env : TemplateEnv,
) -> String {
  match env.sources.get(name.to_owned()) {
    Some(source) =>
      (engine_of(env, name).render_named)(
        name.to_owned(),
        source,
        ctx,
        Some(body_html.to_owned()),
      )
    None => body_html.to_owned()
  }
}

// Render one Liquid template. Liquid does not escape by default, and `include`
// resolves through the templates registered on the context.

///|
fn render_liquid(
  source : String,
  ctx : Json,
  templates : Map[String, String],
  body_html : String?,
) -> String {
  let template = match @liquid.compile(source) {
    Ok(t) => t
    Err(diags) => return ""
  }
  let context = @liquid.LiquidContext::new()
  match ctx {
    Json::Object(map) =>
      for key, value in map {
        context.set(key, to_liquid(value))
      }
    _ => ()
  }
  match body_html {
    Some(html) => {
      context.set("body", @liquid.string_value(html))
      context.set("content", @liquid.string_value(html))
    }
    None => ()
  }
  for name, text in templates {
    context.register_template(name, text)
  }
  match template.render(context) {
    Ok(html) => html
    Err(diags) => ""
  }
}

// Join Liquid diagnostics into one readable line.

///|
fn liquid_errors(diags : Array[@liquid.Diagnostic]) -> String {
  diags.map(fn(d) { d.to_json().stringify() }).join("; ")
}

// Convert the pipeline's JSON tree into a Liquid value.

///|
fn to_liquid(value : Json) -> @liquid.LiquidValue {
  match value {
    Json::Null => @liquid.null_value()
    Json::True => @liquid.bool_value(true)
    Json::False => @liquid.bool_value(false)
    Json::Number(n, ..) => @liquid.number_value(n)
    Json::String(s) => @liquid.string_value(s)
    Json::Array(items) =>
      @liquid.array_value(items.map(fn(item) { to_liquid(item) }))
    Json::Object(map) => {
      let result : Map[String, @liquid.LiquidValue] = Map([])
      for key, item in map {
        result.set(key, to_liquid(item))
      }
      @liquid.object_value(result)
    }
  }
}

///|
/// Mark a string as trusted HTML for templates that need it explicitly.
pub fn safe_html(s : StringView) -> Json {
  Json::string(s.to_owned())
}