#!/usr/bin/env python
#
#
from urllib2 import urlopen
# installed by hand right now. might put it in one package. python-pdi
from pdi.icalendar import VCalendar,ICalendar
import pdi.parser
import time
from sys import exit,stdout
import re_codec

def print_log(string):
	print time.strftime("%Y-%m-%d %H:%M:%S"),"\t:",string
	stdout.flush()

def get_new_ical_from_url(url):
	#update ical file.
	#this needs to go somethere else
	t_filename="%s.t"%re_codec.re_ics_cache_file
	filename=re_codec.re_ics_cache_file
	try:
		ics_fh=urlopen(url)
	except:
		return None
	try:
		ics=ics_fh.read()
		t=open(t_filename,"w")
		t.write(ics)
		t.close()
	except:
		print_log("coudn't get the ical file")
		ics_fh.close
		return None
	ics_fh.close
	try:
		t=open(t_filename,"r")
		new_calendar = pdi.parser.fromFileObject(t, ICalendar())
		t.close
	except:
		print_log("coudn't parse the ics file.")
		return None
	# so the new ical file is valid
	t=open(filename,"w")
	t.write(ics)
	t.close()

if __name__ == '__main__':
	get_new_ical_from_url(re_codec.re_ics_url)

