#!/usr/bin/env python
#
# part of
# re.codec is not a real codec
#
# ical2oggcomment - get dates from ical file and update the ogg comments for ices.
#										right now only the date once an hour.
#
# (c) 2004 <j@reooot.fm>
#

from time import *
from os import system
from urllib2 import urlopen
from pdi.icalendar import VCalendar,ICalendar
import pdi.parser

comments_file="/tmp/oggcomments"
update_comment_cmd="killall -SIGUSR1 ices2 > /dev/null 2>&1"
ics_url="http://localhost/current2.ics"
default_comment="title=reboot.fm live broadcast\n"

# the latest verion is in restream.py dont know yet how to sync them.
# but its only based on upcoming_show
# return default comment if something goes wrong or there is no show running 
def current_show():
	global default_comment
	shows= {}
	comment=default_comment
	comment +="date=%s\n" % strftime("%Y-%m-%d %H:00") # add the current date to comment.
	
	try:
		ics_fh=urlopen(ics_url)
		calendar = pdi.parser.fromFileObject(ics_fh, ICalendar())
	except:
		return comment
		
	ics_fh.close
	#<year><month><day>T<hour><minute<second><type designator>
	icaltimeformat_utc="%Y%m%dT%H%M%SZ"
	# its always localtime. timezones are stored in TZID not willing to
	# reimplement that here. still looking for a better ical lib.
	# or implememnt it in pdi so that DTSTART provides i.e. getContentAsTime()
	#<year><month><day>T<hour><minute<second>	
	icaltimeformat="%Y%m%dT%H%M%S"
	for show in calendar.components:
		try:
			next_show=strptime(show.properties['DTSTART'].getContent().strip(), icaltimeformat)
			next_show_end=strptime(show.properties['DTEND'].getContent().strip(), icaltimeformat)
		except:
			next_show=strptime(show.properties['DTSTART'].getContent().strip(), icaltimeformat_utc)
			next_show_end=strptime(show.properties['DTEND'].getContent().strip(), icaltimeformat_utc)
		if int(mktime(next_show_end)) > int(time()) and int(mktime(next_show)) <= int(time()):
			comment = "title=%s\n" % show.properties['SUMMARY'].getContent().strip()
			comment +="artist=reboot.fm\n"
			comment +="album=reboot.fm\n"
			comment +="date=%s\n" % strftime("%Y-%m-%d %H:%M",next_show)

	return comment


def print_oggcomment_to_file():
	global comments_file,update_comment_cmd
	
	#comment  =  "title=live form studio A\n"
	#comment =  comment + "artist=reboot.fm\n"
	#comment =   comment + "album=reboot as long as you can\n"
	#comment =    comment +"date=%s\n" % strftime("%Y-%m-%d %H:%M")

	# get current show.
	comment=current_show()
	
	if comment: # only if there is a comment do the update
		try:
			file = open(comments_file,"r")
			comment_old= file.read()
			file.close()
		except:
			comment_old=""
		if comment != comment_old:
			file = open(comments_file,"w")
			file.write(comment)
			file.close()
			system(update_comment_cmd)

#main
if __name__ == '__main__':
	while 1:
		if strftime("%M") == "00":
			print_oggcomment_to_file()
			sleep(3500)
