#!/usr/bin/env python
# -*- coding: utf8 -*-

import json
import sys
import time
import urllib

if __name__ == "__main__":
    import sys

    if len(sys.argv) != 2:
        print("usage: %s output_file" % sys.argv[0])
        exit(1)

    path = sys.argv[1]

    json_response = urllib.urlopen("http://www.dagensmiddag.net/index.json").read()
    response = json.loads(json_response)

    weekday = time.localtime().tm_wday

    htm = """<!doctype html>
<head>
    <title>Dagens middag</title>
    <link rel="stylesheet" href="style.css" type="text/css">
</head>\n"""

    htm += "<table>\n<thead><tr>\n"
    htm += 2 * """<th class="leftmost"></th>\n"""

    days = u"Mandag", u"Tirsdag", u"Onsdag", u"Torsdag", u"Fredag", u"Lørdag", u"Søndag"
    for i in range(len(days)):
        if not i == weekday:
            continue

        htm += """<th class="today">%s</th>\n""" % days[i]

    htm += "</tr></thead>\n"

    htm += "<tbody>\n"

    i = 0
    for cafe in response["cafes"]:
        name = cafe["name"]
        menu = cafe["menu"]
        opening_hours = cafe["open"]

        if i % 2 == 0:
            row_class = "even"
        else:
            row_class = "odd"

        htm += """<tr class="%s">\n""" % row_class

        num_dish_types = len(menu[weekday])

        htm += u"""<td class="leftmost" rowspan="%d">%s</td>\n""" % (num_dish_types + 1, name)
        htm += u"""<td>Åpningstid</td>\n"""
        htm += u"""<td>%s</td>\n""" % opening_hours[weekday]

        htm += "</tr>\n"

        for dt in menu[weekday]:
            htm += u"""<tr class="%s">\n""" % row_class
            htm += u"""<td>%s</td>\n""" % dt

            column_class = "today"
            htm += u"""<td class="%s"><ul>\n""" % column_class
            for j in menu[weekday][dt]:
                htm += u"""<li>%s</li>\n""" % j
            htm += u"""</ul></td>\n"""

            htm += u"""</tr>\n"""

        i += 1

    htm += "</tbody>\n"
    htm += "</table>\n"

    htm += u"""<div class="notice">
    <p>Denne siden er laget av Martin Stensgård (mastensg&#64;ping.uio.no).</p>
    <p>Tabellen fins også som <a href="index.json">JSON</a>.</p>
    <p>Kildekoden er tilgjengelig på <a href="http://github.com/mastensg/dagensmiddag">Github</a>.</p>
</div>"""

    f = open(path, "w")
    f.write(htm.encode("utf-8"))
    f.close()
