module JamRuby
  class CalendarManager < BaseManager
    DATE_FORMAT="%Y%m%dT%H%M%SZ"
    def initialize(options={})
      super(options)
      @log = Logging.logger[self]
    end

    def cancel_ics_event(music_session, user)
      Calendar.where(
                user_id: user.id,
                target_uid: music_session.id,
                name: music_session.description)
              .first_or_create(
                description: music_session.description,
                start_at: music_session.scheduled_start,
                end_at: music_session.scheduled_start+music_session.safe_scheduled_duration,
                trigger_delete: true)

    end

    # Remove all "delete" event calendar records older than 4 weeks:
    def cleanup()
      Calendar.where("trigger_delete=TRUE AND created_at < ?", 4.weeks.ago)
              .destroy_all()
    end

    # @return event (as ICS string) for a given music session
    def ics_event_from_music_session(music_session, delete=false)
      # Determine properties of calendar event and create:
      uid = "#{music_session.id}@JamKazam"
      text = "JamKazam Session #{music_session.description}"
      rrule = nil
      start_at = music_session.scheduled_start
      stop_at = music_session.scheduled_start+music_session.safe_scheduled_duration
      if !delete && music_session.recurring_mode==MusicSession::RECURRING_WEEKLY
        rrule = "FREQ=WEEKLY;INTERVAL=1"
      end
      create_ics_event(uid, text, text, start_at, stop_at, delete, rrule)
    end

    # @return event (as ICS string) for a given music session
    def ics_event_from_calendar(calendar)
      # Determine properties of calendar event and create:
      rrule = nil
      if !calendar.trigger_delete && calendar.recurring_mode==MusicSession::RECURRING_WEEKLY
        rrule = "FREQ=WEEKLY;INTERVAL=1"
      end

      create_ics_event(
        calendar.target_uid,
        "JamKazam Session #{calendar.name}",
        calendar.description,
        calendar.start_at,
        calendar.end_at,
        calendar.trigger_delete,
        rrule
      )
    end

    # @return calendar (as ICS string) for specified user
    # Includes all RSVPed sessions, as well as any calendar
    # entries for the given user:
    def create_ics_feed(user)
      ics_events = ""
      MusicSession.scheduled_rsvp(user, true).each do |music_session|
        ics_events << "\r\n" if(ics_events.length != 0)
        ics_events << ics_event_from_music_session(music_session)
      end

      user.calendars.each do |user|
        ics_events << "\r\n" if(ics_events.length != 0)
        ics_events << ics_event_from_calendar(user)
      end

      create_ics_cal(ics_events)
    end

    # @return event (as ICS string) for given arguments
    def create_ics_event(uuid, name, description, start_at, end_at, delete=false, rrule=nil, sequence=nil)
      uuid ||= UUID.timestamp_create
      event = "BEGIN:VEVENT\r\n"
      event << "UID:#{uuid}\r\n"
      event << "DTSTAMP:#{Time.now.utc().strftime(DATE_FORMAT)}\r\n"
      event << "DTSTART:#{start_at.utc().strftime(DATE_FORMAT)}\r\n"
      event << "DTEND:#{end_at.utc().strftime(DATE_FORMAT)}\r\n"
      event << "SUMMARY:#{name}\r\n"
      event << "DESCRIPTION:#{description}\r\n"
      if delete
        event << "METHOD:CANCEL\r\n"
        event << "STATUS:CANCELLED\r\n"
      end
      if rrule
        event << "RRULE:#{rrule}\r\n"
      end
      event << "SEQUENCE:#{sequence}\r\n" if sequence
      event << "END:VEVENT"
    end

    # @return calendar (as ICS string) for specified events
    def create_ics_cal(ics_events)
      "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:JamKazam\r\n#{ics_events}\r\nEND:VCALENDAR"
    end

  end # class
end # module