# today_event.rb
# Copyright (C) 2006 Michitaka Ohno <elpeo@mars.dti.ne.jp>
# You can redistribute it and/or modify it under GPL2.

require 'open-uri'
require 'timeout'
require 'rexml/document'
require 'nkf'
require 'time'

@today_event_google_id = 'your google id'

def get_feeds( date )
	day = date.strftime( "%Y-%m-%d" )
	url = "http://www.google.com/calendar/feeds/"
	url << @today_event_google_id
	url << "/public/basic?start-min=#{day}T00:00:00&start-max=#{day}T23:59:59"
	begin
		timeout( 10 ) do
			open( url ) {|f| f.read}
		end
	rescue Exception
		""
	end
end

def get_link( entry )
	entry.elements.to_a( 'link' ).each do |item|
		if item.attributes['type'] == 'text/html' then
			return item.attributes['href']
		end
	end
end

@mode == 'day' && add_body_leave_proc do |date|
	xml = get_feeds( date )
	doc = REXML::Document::new( xml ).root
	a = []
	doc && doc.elements.to_a( '/feed/entry' ).each do |item|
		r = ""
		offset = %r|Asia/Tokyo| =~ item.elements.to_a( 'summary' )[0].text ? Time.now.utc_offset : 0
		time = Time.at( Time.parse( item.elements.to_a( 'published' )[0].text ).to_i - offset )
		link = get_link( item )
		title = item.elements.to_a( 'title' )[0].text
		r << %Q[<li><span class="event-time" title="#{time}">#{time.strftime( '%H:%M' )}</span>&nbsp;<a class="event-title" href="#{link}">#{NKF::nkf( '-m0 -We', title )}</a>&nbsp;]
		dates = time.getutc.strftime( '%Y%m%dT%H%M%SZ' )
		r << %Q[<a class="event-share" title="この予定を共有" href="http://www.google.com/calendar/event?action=TEMPLATE&text=#{CGI::escape( title )}&dates=#{dates}/#{dates}"><img src="http://www.google.com/calendar/images/ext/gc_button1.gif" border="0"></a></li>]
		a << r
	end
	if a.empty? then
		""
	else
		<<-HTML
		<div class="section">
		<h3>今日の予定 powered by <a href="http://www.google.com/calendar/">Google Calendar</a></h3>
		<ul>#{a.sort.to_s}</ul>
		</div>
		HTML
	end
end

