#!/usr/bin/python

# parse ical calendar and insert values into html template

import requests
import arrow
from ics import Calendar
from jinja2 import Environment, FileSystemLoader
import os


url = 'https://portal.idiv.de/ssf/ical/basic.ics?bi=393&ui=1026&pd=171497477d81eb659bd832ffe26c8bfe39d65fc3&v=1'
tz = 'Europe/Berlin'
now = arrow.now(tz)
period = (now.floor('day'), now.replace(weeks=+52))


c = Calendar(requests.get(url).text)
html_list = []
for e in c.events:
    if e.end > period[0] and e.begin < period[1]:
    # only display events which have not ended yet
    # and start earlier than defined above
        duration = e.end - e.begin
        # short, full day and multi day events display datetime differently
        if duration.days < 1:
            event_date = (e.begin.format('DD.MM.YYYY, HH:mm')
                          + ' &ndash; '
                          + e.end.format('HH:mm'))
        elif duration.days == 1:
            event_date =  e.begin.format('DD.MM.YYYY') + ', all day'
        elif duration.days > 1:
            # in ics file the end date is the day after end date at 00:00:00
            corrected_end_date = e.end.replace(days = - 1)
            event_date = (e.begin.format('DD.MM.YYYY')
                          + ' &ndash; '
                          + corrected_end_date.format('DD.MM.YYYY'))
        else:
            event_date = ''
        # create list of dictionaries for jinja2 template
        event = dict(date = event_date, name = e.name, location = e.location)
        html_list.append(event)

# Capture our current directory
this_dir = os.path.dirname(os.path.abspath(__file__))

# Create the jinja2 environment.
# Notice the use of trim_blocks, which greatly helps control whitespace.
j2_env = Environment(loader=FileSystemLoader(this_dir),
                     trim_blocks=True)
output = j2_env.get_template('template.html').render(html_list = html_list)
out_file = open(this_dir + "/website/events.html", "w")
out_file.write(output.encode("utf-8"))
out_file.close()