module EventsHelper
  # Returns the next (num_events) upcoming events. If there are not that many,
  # we fill out the list with the most recent events.
  def upcoming_and_recent_events(num_events)
    today_i = Date.today.to_time.to_i
    valid_start = "(event.event_start_display_date IS NULL) OR " \
                  "(event.event_start_display_date <= #{today_i})"
    valid_end = "(event.event_end_display_date IS NULL) OR " \
                "(event.event_end_display_date > #{today_i})"
    valid = "(event.status = 'Approved') AND (#{valid_start}) AND (#{valid_end})"

    if num_events.nil?
      return Event.as(:event).
                   where(valid).
                   order(event_date: :desc).
                   to_a
    end

    events = Event.as(:event).
                   limit(num_events).
                   where("(event.event_date >= #{today_i}) AND #{valid}").
                   order(event_date: :asc).
                   to_a
    if events.length < num_events
      events += Event.as(:event).
                      limit(num_events - events.length).
                      where("(event.event_date < #{today_i}) AND #{valid}").
                      order(event_date: :desc).
                      to_a
    end
    # sort in descending order
    events.sort_by(&:event_date).reverse
  end
end
