module TopicPolicy
  class << self
    def user_can_see_future_or_held_topics?(user)
      user && [:admin, :expert].include?(user.role)
    end   
    
    # Block access to 'private' topics, unless the user is on the access list
    def topic_scope_for_user(user)
      case user
      when Admin # can see all
        {}
      when Expert # cannot see private topics, unless on access list
        {
          :conditions => [not_private_or_on_access_list, user.accessible_topic_ids]
        }
      when RegisteredUser # can see approved topics, with the right date, that are 
                          # either not private, or the user is on the access list
        {
          :conditions => ["approved = 1 && `start_date` <= ? && #{not_private_or_on_access_list}", Date.today, user.accessible_topic_ids]
        }
      when Guest # can see approved topics, with the right date, that are not private
        {
          :conditions => ['approved = 1 && `start_date` <= ? && private != 1', Date.today] 
        }
      else
        throw "Unrecognized user type: #{user}"
      end
    end
    
    def not_private_or_on_access_list
      "(private != 1 || #{Topic.table_name}.id in (?))"
    end

  end     
end