#! /usr/bin/env python3

import yaml
import os
import sys
import markdown
import calcdb

db = calcdb.CalcDB(".")
md = markdown.Markdown()

# Fields for the summary
summary = [
  "teaching.exam_mode",
  "devices.transfer_tutorial",
]

# Parse arguments

def usage():
    print(f"usage: {sys.argv[0]} <lang> [--standalone]", file=sys.stderr)
    sys.exit(1)

args = sys.argv[1:]
if len(args) < 1:
    usage()

if args[0] not in db.lang:
    print(f"error: no language data for '{args[0]}'", file=sys.stderr)
    sys.exit(1)
lang = db.lang[args[0]]

if args[1:] != [] and args[1:] != ["--standalone"]:
    usage()
standalone = ("--standalone" in args)

# HTML bits

header = """
<!doctype html>
<html>
  <head>
    <meta charset='utf-8'>
    <style>
      * { box-sizing: border-box; }
      body { font-family: "DejaVu Sans", sans-serif; font-size: 12px; }
      table { border-collapse: collapse; width: max-content; }

      /* Layout of cells */
      th:not(.borderless), td:not(.borderless) {
        border: 1px solid #e0e0e0;
        border-width: 1px 1px 0 1px;
      }
      th { width: 256px; max-width: 256px; padding: 6px; text-align: right; }
      td { width: 144px; max-width: 144px; padding: 6px; text-align: center; }
      tr:nth-child(2n+4) {
        background: #f4f4f4;
      }

      /* Headers */
      tr.category {
        background: #e0e0e0;
        border: 1px solid #808080;
      }
      tr.category > * {
        border: none;
      }
      tr.category + tr > * {
        border-top: none;
      }
      th.category { font-weight: bold; }
      th.field { font-weight: normal; }

      /* Styles */
      td.st-mono   { font-family: monospace; }
      td.st-bad    { background: #f9d6d6; color: #aa2222; }
      td.st-warn   { background: #fdeac7; color: #995004; }
      td.st-good   { background: #dde8cb; color: #115511; }
      td.st-active { background: #dde8cb; border: 1px solid #89a855; }

      /* Layout in cells */
      td {
        line-height: 150%;
      }
      td > img {
        max-width: 100%;
        max-height: 120px;
        text-align: center;
      }
      td > p {
        margin: 0;
        padding: 0;
      }

      a, a:visited { color: #be1818; text-decoration: none; }
      a:hover { text-decoration: underline; }
    </style>
  </head>
  <body>"""

if standalone:
    print(header)
print("<table>")

# Photo
print(f"<tr><th class='borderless field'></th>")
for (name, calc) in db.all_calcs():
    if standalone:
        url = f"../images/small/{name}.jpg"
    else:
        url = "https://git.planet-casio.com/Lephenixnoir/CalcDB/raw/"\
            f"branch/master/images/small/{name}.jpg"

    cssname = "calc calc-" + name.replace("+", "p")
    print(f"<td class='borderless {cssname}'><img src='{url}'></td>")
print("</tr>")
# Full name
print(f"<tr><th class='borderless field'></th>")
for (name, calc) in db.all_calcs():
    value = calc["general"]["full_name"]
    active = " st-active" if calc["general"]["active"] else ""

    cssname = "calc calc-" + name.replace("+", "p")
    print(f"<td class='borderless {cssname}{active}'><b>{value}</b></td>")
print("</tr>")

# First category, the "summary"
for category in ["summary"] + db.all_categories():
    r = lang.category(category)
    print(f"<tr class='category'>")
    print(f"  <th class='category'>{r}</th>")
    print(f"  <td colspan={len(db.calcs)}></td>")
    print(f"</tr>")

    if category == "summary":
      fields = (name.split(".", 1) for name in summary)
    else:
      fields = ((category, field) for field in db.all_fields(category))

    for (cat, field) in fields:
        if category == "general" and field == "full_name":
            continue

        r = lang.field(cat, field)
        print(f"<tr><th class='field'>{r}</th>")

        for (name, calc) in db.all_calcs():
            value = calc.get(cat,{}).get(field)

            r, styles = calcdb.render(db, lang, cat, field, value)
            r = lang.filter(r)
            r = md.convert(r)

            classes = " ".join(f"st-{c}" for c in styles)
            cssname = "calc calc-" + name.replace("+", "p")
            print(f"<td class='{cssname} {classes}'>{r}</td>")
        print("</tr>")

print("</table>")
if standalone:
    print("</body></html>")
