module TopicsHelper
  
  # return the name of the lastest commenter on a given topic
  def latest_commenter_on(topic)
    topic.comments.most_recent.user.name rescue nil
  end
  
  def edit_links(topic)
    if current_user.has_permission_to?(:topics_edit)
      
      str = String.new
      
      str << edit(topic) if current_user.has_permission_to?(:topics_edit)
      
      if current_user.has_permission_to?(:topics_approve)
          if topic.approved?
            str << hold(topic)
          else
            str << approve(topic)
          end
      end
        
      str << " (not yet available)" if topic.for_future?

      if current_user.has_permission_to?(:library_new) 
        str << add({:controller => 'library', :id => topic.id}, "add support material")
      end

      content_tag(:p, str)
    end
  end
  
  def show_hot_comments?
    !@most_read_comments.empty? && !@highest_rated_comments.empty?
  end
  
  def topic_pubDate(topic)
    CGI.rfc1123_date Time.parse(topic.start_date.to_s)
  end
  
  def library_box(topic)
    return unless ApplicationPolicy::show_support_material?
    render :partial => 'library_box', :locals =>{:topic => topic}    
  end
  
  def comment_children_of(comment)
    # use the cache if available
    if @topic_all_comment_children_ids && @topic_all_comments_by_id
      children_ids = @topic_all_comment_children_ids[comment.id]
      return [] unless children_ids
      return children_ids.collect{|id| @topic_all_comments_by_id[id]}
    else # fallback to querying the object
      return comment.children
    end

  end
  
  def comment_has_children?(comment)
    # use the cache if available
    if @topic_all_comment_children_ids
      return @topic_all_comment_children_ids[comment.id]
    else # fallback to querying the object
      comment.children.length > 0
    end
    
  end
  
end
