<% require 'ri_cal'
require 'digest/sha1'

upcomingEvents = get_public_events().select { |e| e[:startdate].to_datetime > DateTime.now }
upcomingEvents.sort! { |a,b| a[:startdate].to_datetime <=> b[:startdate].to_datetime }

cal = RiCal.Calendar do |cal|
  upcomingEvents.each do |e|
    cal.event do |event|
      event.summary = e[:title]
      event.description = ""
      if e[:startdate].instance_of?(Date)
        event.dtstart = e[:startdate]
        event.dtend = (e[:enddate]+1)  # Unclear RFC definition, see http://www.bedework.org/trac/bedework/wiki/Bedework/DevDocs/DtstartEndNotes
      else
        event.dtstart = e[:startdate].getutc
        event.dtend = e[:enddate].getutc
      end
      if e[:location]
        if e[:location][:details]
          event.location = "#{e[:location][:name]}, #{e[:location][:details]}"
        else
          event.location = e[:location][:name]
        end
      end
      event.uid = Digest::SHA1.hexdigest("#{e[:startdate]}#{e[:title]}")
      if e[:url]
        if e[:url].start_with?('/')
          event.url = "#{@config[:base_url]}#{e[:url]}"
        else
          event.url = e[:url]
        end
      elsif e.identifier.start_with?('/events') or e.identifier.start_with?('/activities')
        event.url = "#{@config[:base_url]}#{e.path}"
        event.uid = Digest::SHA1.hexdigest("#{@config[:base_url]}#{e.path}")
      end
    end
  end
end
%><%= cal.to_s.strip %>
