#!/usr/bin/python

import glob
import markdown
import os
import shutil
from datetime import datetime

# from finch import FinchLexer

TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Wren - {title}</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<link href='http://fonts.googleapis.com/css?family=Sanchez:400|Source+Sans+Pro:300,400,700,400italic,700italic|Source+Code+Pro:300,400' rel='stylesheet' type='text/css'>
</head>
<body id="top">
<a href="https://github.com/munificent/wren">
  <img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub">
</a>
<div class="header">
  <div class="column">
    <h1><a href="index.html">wren</a> <small>a scripting language</small></h1>
    <ul>
      <li><a href="index.html">welcome</a></li>
      <li><a href="syntax.html">syntax</a></li>
      <li><a href="classes.html">classes</a></li>
      <li><a href="usage.html">usage</a></li>
    </ul>
  </div>
</div>
<div class="column">
<h1>{title}</h1>
{html}
<p class="footer">Last modified on {mod}. By Bob Nystrom.</p>
</div>
</body>
</html>
"""

def format_file(path):
  basename = os.path.basename(path)
  basename = basename.split('.')[0]

  title = ""

  # Read the markdown file and preprocess it.
  contents = ""
  with open(path, "r") as input:
    # Read each line, preprocessing the special codes.
    for line in input:
      stripped = line.lstrip()
      indentation = line[:len(line) - len(stripped)]

      if stripped.startswith("^"):
        command,_,args = stripped.rstrip("\n").lstrip("^").partition(" ")
        args = args.strip()

        if command == "title":
          title = args
        else:
          print "UNKNOWN COMMAND:", command, args

      else:
        contents = contents + line

  html = markdown.markdown(contents, ['def_list', 'codehilite'])

  modified = datetime.fromtimestamp(os.path.getmtime(path))
  mod_str = modified.strftime('%B %d, %Y')

  fields = {'title': title, 'html': html, 'mod': mod_str}

  # Write the html output.
  with open("build/site/" + basename + ".html", 'w') as out:
    out.write(TEMPLATE.format(**fields))

  print "converted", basename

# Clean the output directory.
if os.path.exists("build/site"):
  shutil.rmtree("build/site")
os.mkdir("build/site")

# Process each markdown file.
for f in glob.iglob("doc/site/*.markdown"):
  format_file(f)

# Copy the CSS file.
shutil.copyfile("doc/site/style.css", "build/site/style.css")
