# Schema as of Mon Nov 27 15:17:56 EST 2006 (schema version 35)
#
#  id                  :integer(11)   not null
#  name                :string(255)   default(), not null
#  url                 :string(255)   default()
#  topic_id            :integer(11)   default(0), not null
#  reading_count       :integer(11)   
#  filename            :string(255)   
#  content_type        :string(255)   
#  size                :integer(11)   
#  parent_id           :integer(11)   
#

class SupportMaterial < ActiveRecord::Base  
  acts_as_attachment :content_type => ['application/pdf', 'text/html'],
    :file_system_path => 'private'

  belongs_to :topic
  
  has_many   :readings,
             :as => :readable,
             :dependent => :destroy
             
  has_many   :informative_ratings,  
             :dependent => :destroy, 
             :class_name => 'MaterialInformativeRating', 
             :foreign_key => 'subject_id',
             :extend => RatingForUserAssociationExtension

  has_many   :convincing_ratings,  
             :dependent => :destroy, 
             :class_name => 'MaterialConvincingRating', 
             :foreign_key => 'subject_id',
             :extend => RatingForUserAssociationExtension
  
  validates_presence_of :topic, :name
  
  validate :not_both_file_and_url

  validate :presence_of_file_or_url
  validate :attachment_attributes_valid_if_no_url
  validates_presence_of :size, :content_type, :filename, :if => Proc.new { |sup| sup.no_url? }
  # TODO if any of these are missing, only one error should be raised. no?
    
  # can this support material be rated -- depend on the topic it is attached to
  def rateable?
    topic && topic.rateable?
  end
  
  # test that either the file or the url are present  
  def presence_of_file_or_url
    errors.add_to_base("A file or a URL is required") unless filename || !url.blank?
  end
  
  # keep users from creating a support material with both a url AND and file
  def not_both_file_and_url
    errors.add_to_base("Cannot have both a file and a URL") if filename && !url.blank?
  end
  
  # A nice title.
  #
  # returns "file #{filename}" for files or "link {url}" for links 
  def title
    url.blank? ? "file #{File.basename(filename)}" : "link #{url}"
  end
  
  def no_url?
    url.blank?
  end
  
  # a wrapper around acts_as_attachements validation so that it can be made conditional
  def attachment_attributes_valid_if_no_url
    attachment_attributes_valid? if no_url?
  end
end
