#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (C) Valentin Samir, Yann Duplouy, Jordan Delorme
# Licence : GPLv2

# Ce script génère une calendrier isc à partir de la page wiki
# https://wiki.crans.org/VieBdS/LesEvenements
print """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Nit Kfet Calendar
X-WR-CALNAME:Sports
BEGIN:VTIMEZONE
TZID:Europe/Paris
X-LIC-LOCATION:Europe/Paris
BEGIN:DAYLIGHT
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
TZNAME:CEST
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=3
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
TZNAME:CET
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=10
END:STANDARD
END:VTIMEZONE
"""

import urllib2
import hashlib
import time
def ftime(str):
	return time.strftime("%Y%m%dT%H%M00", time.strptime(str, '%Y-%m-%d %H:%M'))
for event in urllib2.urlopen("https://wiki.crans.org/VieBdS/LesEvenements?action=raw").read().split('== ')[1:]:
	event=event.split('\r\n')
	title=event[0][:-2].strip()
	start=end=desc=None
	for e in event:
		if e.strip().startswith('start::'):
			start=e.strip()[7:].strip()
		elif e.strip().startswith('end::'):
			end=e.strip()[5:].strip()
                elif e.strip().startswith('recur::'):
                        recur=e.strip()[7:].strip()
                        if recur==('2 week'):
                           recurr='FREQ=WEEKLY;INTERVAL=2'
                        if recur==('1 week'):
                           recurr='FREQ=WEEKLY;INTERVAL=1'   
		elif e.strip().startswith('description::'):
			desc=e.strip()[13:].strip()
                elif e.strip().startswith('location::'):
                        loc=e.strip()[10:].strip()
        if int(start[0:4]) < (time.localtime()[0]-1):
            continue
	print """BEGIN:VEVENT
UID:%s
SUMMARY:%s
DTSTART;TZID=Europe/Paris:%s
RRULE:%s
DTEND;TZID=Europe/Paris:%s
DESCRIPTION:%s
LOCATION:%s
END:VEVENT
""" % (hashlib.md5(title + start + recurr + end + desc + loc).hexdigest(), title,  ftime(start), recurr, ftime(end), desc, loc)
		
print "END:VCALENDAR"
