#!/usr/bin/env python2.7
import re
import sys
import os
import os.path
import shutil
import subprocess
# import commonmark # install `pip install --user CommonMark` (currently CommonMark-0.8.1)
import markdown

def split_lean(name):
  (root, ext) = os.path.splitext(name)
  print "SPLIT", root
  inp = open(name)
  sheet = open(root + "_sheet" + ext, "w")
  solution = open(root + "_solution" + ext, "w")

  in_solution = False
  for l in inp:
    if l.startswith("--sol "):
      if in_solution:
        print "WARNING: missing --los"
      else:
        in_solution = True
      sheet.write(l[6:])
    elif l.startswith("--los"):
      if not in_solution:
        print "WARNING: missing --sol"
      else:
        in_solution = False
    else:
      if not in_solution:
        sheet.write(l)
      solution.write(l)

def prepare():
  for root, dirs, files in os.walk('.'):
    for f in files:
      if re.match("\d\d_homework.lean", f):
        split_lean(os.path.join(root, f))
      elif re.match("\d\d_exercise.lean", f):
        split_lean(os.path.join(root, f))

def convert_markdown(title, f):
  (base, ext) = os.path.splitext(f)
  print "MARKDOWN -> HTML: ", base

  md = open(f, "r").read().decode("utf-8")
  html = markdown.markdown(md, extensions=["markdown.extensions.tables"])
  out = open(base + ".html", "w")
  out.write("<!DOCTYPE html>")
  out.write("<html>")
  out.write("<head>")
  out.write("<title>%s</title>" % title)
  out.write("<meta charset=\"UTF-8\">")
  out.write("""<style>
    body {
      margin-top: 2em;
      margin-left: 2em;
      margin-right: 2em;

      font-family: sans-serif;
    }
    code {
      color: #8B0000;
    }
    th { padding-left: 1ex; text-align: left; }
    td { padding-left: 1ex; text-align: left; }
    thead th { border-bottom: 1px solid black; }
  </style>""")
  out.write("</head>")
  out.write("<body>")
  out.write(html.encode("utf-8"))
  out.write("</body></html>")

def copy(names):
  new_files = []
  for root, dirs, files in os.walk('.'):
    if not re.match("\./\d_.*", root):
      continue
    for f in files:
      (base, ext) = os.path.splitext(f)
      if base in names:
        print "COPY", base
        shutil.copy(os.path.join(root, f), "./web")
        names.remove(base)
        new_files.append(os.path.basename(f))
        if ext == ".md":
          convert_markdown(base, os.path.join("./web", f))
          new_files.append(base + ".html")

  if names:
    print "WARNING: Didn't find the following files to copy", names

  print "GIT ADD: ", new_files
  subprocess.call(["git", "add"] + new_files, cwd="./web")


print "GIT PULL"
if subprocess.call(["git", "pull"], cwd="./web") != 0:
  print "ERROR: 'git pull' failed"
  sys.exit(1)

prepare()
copy(set([
  "11_notes", "11_lecture", "11_exercise_sheet", "11_homework_sheet", "11_exercise_solution", # "11_homework_solution",
  "12_notes", "12_lecture", "12_exercise_sheet", "12_homework_sheet", "12_exercise_solution", # "12_homework_solution",
  "13_notes", "13_lecture", "13_exercise_sheet", "13_homework_sheet", "13_exercise_solution", # "13_homework_solution",
  "21_notes", "21_lecture", "21_exercise_sheet", "21_homework_sheet", "21_exercise_solution", # "21_homework_solution",
  "22_notes", "22_lecture", "22_exercise_sheet", "22_homework_sheet", "22_exercise_solution", # "22_homework_solution",
  "23_notes", "23_lecture", "23_exercise_sheet", "23_homework_sheet", "23_exercise_solution", # "23_homework_solution",
  "24_notes", "24_lecture", "24_exercise_sheet", "24_homework_sheet", "24_exercise_solution", # "24_homework_solution",
  "31_notes", "31_lecture", "31_exercise_sheet", "31_homework_sheet", "x31_library", "31_exercise_solution", # "31_homework_solution",
  "32_notes", "32_lecture", "32_exercise_sheet", "32_homework_sheet", "x32_library", "32_exercise_solution", # "32_homework_solution",
  "33_notes", "33_lecture", "33_exercise_sheet", "x33_library", "33_exercise_solution",
  "41_notes", "41_lecture", "41_exercise_sheet", "41_exercise_solution",
  "42_notes", "42_lecture",
  "43_notes", "43_lecture",
]))

print "Please commit and push in web"
