import os
import sys
import urllib.request
import datetime
import time
import re
import itertools

def main(date):
  dishes = []
  pdf = "/tmp/MA-aktuell.pdf"
  url = "http://personalkantine.personalabteilung.tu-berlin.de/pdf/MA-aktuell.pdf"
  menu = "/tmp/MA-aktuell.txt"

  urllib.request.urlretrieve(url, pdf)
  os.system("pdftotext -layout -nopgbrk " + pdf + " " + menu)
  prepare_menu(menu)

  # find current date, offset and header line numbers
  with open(menu) as f:
    in_date_range = False
    wrapped = False
    startline = -1
    endline = -1

    # jump to start of file
    f.seek(0, 0)
    for i, line in enumerate(f):
      dishes = []
      line = line.rstrip()

      # check for not price finished line (occurs after friday)
      if in_date_range:
        if not line.endswith("€"):
          if not wrapped:
            wrapped = True
          else:
            endline = i-1
            in_date_range = False
        else:
          if wrapped:
            wrapped = False

      # check for next date
      if not wrapped and in_date_range:
        exp = re.compile('^\d\d\.\d\d\.\d\d ')
        if exp.match(line):
          endline = i-1
          in_date_range = False

      # find start line (MUST be after checking for next date)
      if line.startswith( date ):
        startline = i-1
        in_date_range = True

    f.seek(0, 0)

    if startline == -1 or endline == -1:
      return ["Date not found"]

    lines = itertools.islice(f, startline, endline)
    for line in lines:
      line = line.rstrip()

      # remove date tag
      exp = re.compile('^\d\d\.\d\d\.\d\d ')
      line = exp.sub('', line)

      # remove day tag
      exp = re.compile('^(Montag|Dienstag|Mittwoch|Donnerstag|Freitag), ')
      line = exp.sub('', line)

      # replace "vegetarisch" with "(v)"
      exp = re.compile('^vegetarisch')
      line = exp.sub('(v)', line)

      # use common price tag design
      exp = re.compile(' +(\d,\d+) +€$')
      line = exp.sub(': \g<1>€', line)

      dishes.append(line)

  # cleanup
  os.system("rm " + pdf + " " + menu)
  return dishes

def get_menue(date):
  dishes = main(date)
  menue = ""
  for dish in dishes:
    menue = menue + dish + "\n"
  menue = menue.rstrip()
  return menue

def prepare_menu(f):
  new_menue = []
  with open(f, 'r') as menu:
    for line in menu:
      # remove indregend hints (e.g. '(Sch)')
      exp = re.compile('\([\w +]+\)')
      line = exp.sub('', line)

      # reduce whitespace
      exp = re.compile('[ \t]+')
      line = exp.sub(' ', line)

      # remove leading whitespace
      exp = re.compile('^ ')
      line = exp.sub('', line)

      # remove empty lines
      if line.strip():
        new_menue.append(line)

  with open(f, 'w') as menu:
    menu.writelines(new_menue)

if __name__ == '__main__':
  print( get_menue( datetime.date.today().strftime("%d.%m.%y")))

# vim:set ft et sw=2 sts=2:

import os
import sys
import datetime
import time
import re
import urllib.request
from bs4 import BeautifulSoup


def main(date):
  dishes = []
  url = "http://personalkantine.personalabteilung.tu-berlin.de/"
  html = urllib.request.urlopen(url).read()
  menu = BeautifulSoup( html, 'html.parser' ).find("ul", class_="Menu__accordion")

  for day in menu.children:
    if day.name and date in day.find("h2").string:
      for dishlist in day.children:
        if dishlist.name == 'ul':
          for dish in dishlist.find_all('li'):
            this_dish = ""
            for string in dish.stripped_strings:
              this_dish = this_dish + " " + string
            this_dish = _format( this_dish )
            dishes.append( this_dish )

  return dishes

def _format(line):
  line = line.strip()

  # remove indregended hints
  exp = re.compile('\([\w\s+]+\)')
  line = exp.sub('', line)

  # use common price tag design
  exp = re.compile('\s+(\d,\d+)\s+€')
  line = exp.sub(': \g<1>€', line)

  return line

def get_menue(date):
  dishes = main(date)
  menue = ""
  for dish in dishes:
    menue = menue + dish + "\n"
  menue = menue.rstrip()
  return menue

if __name__ == '__main__':
  print( get_menue( datetime.date.today().strftime("%d.%m.%Y")))

# vim:set ft et sw=2 sts=2:

rewrite for the new layout (html instead of pdf)