class Attachment < ActiveRecord::Base
  
  attr_accessible :attachable_id, :attachable_type, :content, :downloads, :name, :attachment_category_id
  
  # Non database attributtes
  attr_accessible :thumbnail, :datafile
  
  # Associations
  belongs_to :attachable, polymorphic: true
  belongs_to :attachment_category
  
  # Validations
  validates :name, :attachable_type, :attachable_id, presence: true
  validates :attachment_category_id, presence: true, unless: Proc.new{|o| ["InstitutionService", "Comment", "ForumPost"].include?(o.attachable_type)}
  validates :downloads, numericality: { only_integer: true }, allow_nil: true
  
  # Paperclip
  has_attached_file :datafile

  has_attached_file :thumbnail,
    content_type: ['image/jpeg', 'image/jpg', 'image/png'],
    styles: { thumb: '120x120>' }

  validates_attachment_presence :datafile

  # Callback
  before_validation :ensure_name

  def ensure_name
    if attachable.is_a?(InstitutionService)
      self.name = [attachable.name, attachable.institution_name, Random.rand(9999)].compact.join(' - ') if self.name.blank?
    elsif ( attachable.is_a?(Comment) or attachable.is_a?(ForumPost) )
      self.name = self.datafile_file_name
    end
  end
end
