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

import json
import os
import tempfile
import time

import mechanize
import lxml.html

def parse_page(page):
    doc = lxml.html.fromstring(unicode(page, encoding="utf8"))
    doc_table = doc.find_class("sioArticleBodyText")[0].findall("table")[0]
    html_table = lxml.html.tostring(doc_table)

    fd, path = tempfile.mkstemp("-dagensmiddag")
    try:
        os.write(fd, html_table)
        os.close(fd)
        rendered_table = os.popen("elinks -dump -dump-width 10000 %s 2>/dev/null" % path).read()
    except:
        raise
    finally:
        os.remove(path)

    rendered_table = unicode(rendered_table, encoding="utf-8")

    lines = rendered_table.split("\n")
    lines = [l.replace(u"\xa0", " ") for l in lines]
    lines = filter(lambda x: x.strip().strip() != "", lines)
    lines = [l.rstrip("*") for l in lines]
    lines = [l.rstrip(" ") for l in lines]
    lines = [l.rstrip("L") for l in lines]
    lines = [l.rstrip(" ") for l in lines]
    lines = [l.rstrip("*") for l in lines]
    lines = [l.rstrip(" ") for l in lines]

    cols = []
    end = False
    in_column = False
    for x in range(10000):
        occupied = False
        for line in lines:
            if x >= len(line):
                end = True
                break

            if not line[x].isspace():
                occupied = True
                break

        if end:
            break

        if occupied:
            if not in_column:
                cols.append(x)
                in_column = True
        else:
            in_column = False

    table = []
    for line in lines:
        row = []
        for i in range(len(cols) - 1):
            row.append(line[cols[i]:cols[i + 1]])
        row.append(line[cols[-1]:])

        row = [c.strip() for c in row]

        table.append(row)

    for i in range(len(table)):
        for r in range(len(table)):
            if r == 0:
                continue

            if table[r][-1][0].islower():
                table[r - 1][-1] = table[r - 1][-1].rstrip() + " " + table[r][-1].lstrip()
                table.pop(r)
                break

    menu = [{}, {}, {}, {}, {}, {}, {}, {}]
    days = u"Mandag", u"Tirsdag", u"Onsdag", u"Torsdag", u"Fredag", u"Lørdag", u"Søndag"
    day = 0
    dish_types = "Dagens", "Vegetar", "Halal", "Suppe", "Optima"
    dish_type = "Dagens"
    for row in table:
        for c in row[:-1]:
            for d in days:
                if d.lower() in c.lower():
                    day += 1
            for t in dish_types:
                if t.lower() in c.lower():
                    dish_type = t

        if not dish_type in menu[day]:
            menu[day][dish_type] = []

        menu[day][dish_type].append(row[-1])

    if day == 0:
        menu = 5 * [menu[0]] + [{}, {}]
    else:
        menu = menu[1:]

    return menu

if __name__ == "__main__":
    import sys

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

    path = sys.argv[1]

    br = mechanize.Browser()

    br.open("http://www.sio.no/")

    time.sleep(1)
    br.follow_link(text_regex=r"Mat og drikke")

    time.sleep(1)
    br.follow_link(text_regex=r"Dagens middag")

    pages = [
            {"name": "Frederikke Kafé",     "link": r"Frederikke",  "open": ("11:00-19:00", "11:00-19:00", "11:00-19:00", "11:00-19:00", "11:00-18:00", "Stengt", "Stengt")},
            {"name": "Informatikkafeen",    "link": r"Informatikk", "open": ("11:00-17:00", "11:00-17:00", "11:00-17:00", "11:00-17:00", "11:00-15:00", "Stengt", "Stengt")},
            {"name": "Kafé Athletica",      "link": r"Athletica",   "open": ("13:00-21:00", "13:00-21:00", "13:00-21:00", "13:00-21:00", "13:00-18:00", "Stengt", "Stengt")},
            {"name": "Kafé Helga",          "link": r"Helga",       "open": ("11:30-16:30", "11:30-16:30", "11:30-16:30", "11:30-16:30", "11:30-15:30", "Stengt", "Stengt")},
            {"name": "Kafé Ole",            "link": r"Ole",         "open": ("13:00-16:30", "13:00-16:30", "13:00-16:30", "13:00-16:30", "13:00-16:00", "Stengt", "Stengt")},
            {"name": "SV-kafeen",           "link": r"SV.kaf",      "open": ("11:00-18:00", "11:00-18:00", "11:00-18:00", "11:00-18:00", "11:00-15:00", "Stengt", "Stengt")},
            ]

    cafes = []

    for page in pages:
        link = page["link"]

        time.sleep(1)
        response = br.follow_link(text_regex=link)

        menu = parse_page(response.read())
        cafe = {"name": page["name"], "open": page["open"], "menu": menu}
        cafes.append(cafe)

        br.back()

    week = int(time.strftime("%W"))

    f = open(path, "w")
    json.dump({"week": week, "cafes": cafes}, f)
    f.close()
