sitegen = require "sitegen"
Site = require "sitegen.site"
Path = require "sitegen.path"
html = require "sitegen.html"
common = require "sitegen.common"
cosmo = require "sitegen.cosmo"
date = require "date"

import tag from html
import escape_patt from require "sitegen.common"
import p from require "moon" -- debug

-- Change output dir to what Openresty prefers
Site.config.out_dir = "html/"

-- Configure the command our custom renderer uses to convert markdown to html
rend = "renderers.markdown"
require(rend).cmd = "pandoc --mathjax --lua-filter pygments.lua >"

-- Insert custom renderer in the first position so it will be preferred
table.insert Site.default_renderers, 1, rend

-- Remove "pygments" plugin because it conflicts with pandoc syntax highlighting
Site.default_plugins = for v in *Site.default_plugins
  if v\find "pygments" then continue else v

-- from https://github.com/leafo/sitegen/blob/v0.2/spec/sitegen_spec.moon#L9-L18
get_files = (path, prefix=path) ->
  files = Path.read_exec "find", path, "-type", "f"
  files = [f for f in files\gmatch "[^\n]+"]

  if prefix
    files = for file in *files
      file\gsub "^#{escape_patt prefix}/?", ""

  table.sort files
  files

-- strip file extension from filename
rootname = (str) ->
  result = string.gsub str, "%..+", ""
  result

reflect = (obj) -> [key for key, value in pairs obj]
last = (list) -> list[#list]
reverse = (list={}) -> [item for item in *list[#list, 1, -1]]

extract_id = (source) -> string.match Path.filename(source), "%a[%w%-]+"
extract_date = (source) -> string.match Path.filename(source), "%d+%-%d%d%-%d%d"
format_date = (str) -> date(str)\fmt "%b %d, %Y"

strip_date = (filename) ->
  filename\gsub "#{escape_patt(extract_date(filename) .. "-")}/?", ""

publish_date = (path using extract_date, format_date) ->
  date = extract_date path
  date, format_date date

target = (path, prefix=".") ->
  filename = rootname last common.split path, "/"
  Path.join prefix, strip_date filename

h = (word) -> word\sub(1, 1)\upper!
t = (word) -> word\sub(2, -1)\lower!
titleize = (word) -> h(word), t(word)

titleize_slug = (slug="") ->
  words = [{ titleize word } for word in *common.split slug, "-"]
  table.concat [head .. tail for { head, tail } in *words], " "

files_from = (path=".") ->
  [Path.join path, file for file in *reverse get_files path]

get_posts = (limit) =>
  pages = @site\query_pages { is_a: "post" }
  table.sort pages, (a, b) -> a.source > b.source
  limit_or_page_count = math.min limit or #pages, #pages
  [post for post in *pages[1, limit_or_page_count]]

sitegen.create =>
  @site_title = "WebDevCat.me"
  @app_name = "stasis"
  @version = "0.2.12"

  -- helpers
  @titleize = (slug) => titleize_slug slug
  @cif = (args, has_block) => cosmo.cif args, has_block

  @list_posts = (arg={}, _) =>
    posts = [post for post in *get_posts @, arg.limit]

    html.build ->
      import section, h3, time, a from tag
      md = @site\get_renderer "sitegen.renderers.markdown"

      return for post in *posts
        {:title, :blurb, :id, publish_date: {iso, pretty}} = post.meta
        url = rootname post\url_for!

        if blurb
          blurb = raw md\render @, blurb
          blurb.text = unpack [v for v in blurb.text\gmatch "<p>(.-)</p>"]

        section {
          h3 { a { title or titleize_slug(id), href: url }}
          time { pretty, datetime: iso }
          "—", blurb, a { "Read post →", class: "read-post-link", href: url }
        }

  add_all = (files) ->
    add path, {
      target: target path, "/posts"
      template: "post"
      is_a: "post"
      publish_date: { publish_date path }
      id: extract_id path
    } for path in *files

  add "index.html", title: "Catalin Mititiuc"
  add "blog.html", title: "Posts", target: "posts/index", template: "blog"
  add_all files_from "docs"

  -- replace post markdown yaml headers with moonscript headers
  filter "docs", (body) =>
    body\gsub "^%-%-%-.-%.%.%.", (yaml_header) ->
      header = yaml_header\gsub "%-%-%-", "{"
      moonscript_header = header\gsub "%.%.%.", "}"
      moonscript_header

  copy "app.css"
  copy "moonscript.css"
