#!/usr/bin/env moon
import Constant from require 'alv'
import opairs from require 'alv.util'
import compile, render, render_meta, layout, autoref, subnav from require 'docs.gen.layout'
import h2, h3, p, ul, li, code from require 'docs.gen.dom'
import get_module from require 'docs.gen.shim'

export OUT

slurp = (file) ->
  file = io.open file, 'r'
  with file\read '*all'
    file\close!

spit = (file, str) ->
  file = io.open file, 'w'
  file\write str
  file\close!
  
{ OUT, module, name } = arg

name or= module
module = get_module module
raw = module!

get_description = (module) ->
  m = module.meta
  return '' unless m

  buf = p m.summary
  if m.description
    buf ..= compile autoref m.description

  buf

spit OUT, layout
  title: "#{name} module reference"
  body: table.concat {
    subnav [a for a in *arg[4,]]
    h2 (code name), ' module reference'
    get_description module
    h3 'index'
    ul for key, node in opairs raw.values
      li render key, node.result, nil, true
    h3 'details'
    ul for key, node in opairs raw.values
      if node.result.meta and node.result.meta.name != key
        continue

      li render key, node.result
  }, ''
