require 'spec_helper'
require 'icalendar'

describe CalendarManager do
  CALENDAR_NAME="Test Cal"

  before :all do
    @genre1 = FactoryGirl.create(:genre)
    @calendar_manager = JamRuby::CalendarManager.new

    # Time resolution is seconds:
    @start = Time.at(Time.now.utc.to_i)
    @stop =(@start+1.hours)
  end

  before(:each) do

  end

  describe "with music sessions" do
    before :all do
      @creator = FactoryGirl.create(:user)
      @music_session = FactoryGirl.create(:music_session, :creator => @creator, :description => CALENDAR_NAME, :genre => @genre1, :scheduled_start=>@start, :scheduled_duration=>3600)
      @music_session.reload
    end

    it "validator detects bad calendar" do
      lambda{verify_ical("Bad medicine calendar")}
        .should raise_error(RuntimeError)
    end

    it "can create calendar feed" do
      ics = @calendar_manager.create_ics_feed(@creator)
      # Basic format checking...there are some online tools that
      # check a lot more, but no ruby libs that I could find:
      lines = ics.split("\r\n")
      lines.should have(12).items
      lines.first.should eq("BEGIN:VCALENDAR")
      lines.last.should eq("END:VCALENDAR")
      lines[-2].should  eq("END:VEVENT")
      verify_ical(ics)
    end
  end

  describe "with manual calendars" do
    before :all do
      @creator = FactoryGirl.create(:user)
      @creator.calendars<<Calendar.new({:name=>CALENDAR_NAME, :description=>"This is a test", :start_at=>(@start), :end_at=>@stop, :trigger_delete=>false, :target_uid=>"2112"})
    end

    it "can create calendar feed" do
      #pending "foobar"
      ics = @calendar_manager.create_ics_feed(@creator)

      # Basic format checking...there are some online tools that
      # check a lot more, but no ruby libs that I could find:
      lines = ics.split("\r\n")
      lines.should have(12).items
      lines.first.should eq("BEGIN:VCALENDAR")
      lines.last.should eq("END:VCALENDAR")
      lines[-2].should  eq("END:VEVENT")
      verify_ical(ics)
    end
  end

  def verify_ical(ics)
    strict_parser = Icalendar::Parser.new(ics, true)
    cals = strict_parser.parse
    cals.should_not be_nil
    cals.should have(1).items

    cal = cals.first
    cal.should_not be_nil
    cal.events.should have(1).items
    event = cal.events.first
    event.should_not be_nil

    event.summary.should eq("JamKazam Session #{CALENDAR_NAME}")
    event.dtstart.to_i.should_not be_nil
    event.dtend.to_i.should_not be_nil
    (event.dtstart).to_time.utc.to_i.should eq(@start.to_i)
    #(event.dtend).to_time.utc.to_i.should eq(@stop.to_i) # can't get it to work
  end
end

