#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
 Copyright (C) 2004 jan gerber <j@reboot.fm>

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Library General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
'''

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)
