#!/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.
'''

# ical2oggcomment - get dates from ical file and update the ogg comments for ices.
#right now only update once an hour.
#might need some change

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

# installed by hand right now. might put it in one package. python-dateutil
from dateutil.parser import *
import time
import datetime



comments_file="/etc/ices2/metadata.txt"
update_comment_cmd="killall -SIGUSR1 ices2 > /dev/null 2>&1"
ics_url="http://100tage.reboot.fm/vcal/current.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= {}
	date_now=parse(time.strftime("%Y%m%dT%H%M%SZ"))
	
	comment=default_comment
	comment +="date=%s\n" % date_now.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=parse(show.properties['DTSTART'].getContent().strip())
			next_show_end=parse(show.properties['DTEND'].getContent().strip())
		except:
			continue
		if next_show_end > date_now and next_show <= date_now:
			comment = "title=%s\n" % show.properties['SUMMARY'].getContent().strip()
			#comment +="artist=reboot.fm\n"
			comment +="album=reboot.fm\n"
			comment += "uid=%s\n" % show.properties['UID'].getContent().strip()
			comment +="date=%s\n" % next_show.strftime("%Y-%m-%d %H:%M")

	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 time.strftime("%M") == "00":
		print_oggcomment_to_file()
		#time.sleep(3500)
		time.sleep(1)

