class Entry < ActiveRecord::Base
  include AttributeEncrypter 

  belongs_to :group
 
  # has_crypted_attribute defines attributes
  # uniquely encrypted with each accociated user's public key.
  # See the AttributeEncrypter README for more info.
  has_crypted_attribute :password
  has_crypted_attribute :username
  has_crypted_attribute :url
  has_crypted_attribute :description

  
  # Note: the methods #username_updated? and #password_updated? are 
  # generated by the has_crypted_attribute method.
  validates_length_of   :username, :within => 1..110, :if => :username_updated?
  validates_presence_of :username

  validates_presence_of :password,              :if => :password_updated?
  validates_presence_of :password_confirmation, :if => :password_updated?
  validates_confirmation_of :password,          :if => :password_updated?
  validates_length_of       :password, :within => 6..40, :if => :password_updated?
  
  validates_uniqueness_of :title, :scope => :group_id
  validates_length_of     :title, :within => 2..110
  validates_presence_of   :title

  validates_length_of :description, :within => 0..110, :allow_blank => true

  validates_presence_of :group
  
  # Delegates write access check to group.
  def allows_write_access_for?(user)
    self.group.allows_write_access_for?(user)
  end

  private
  
    # All users with permission plus the root user.
    def permitted_users
      raise MissingRootUser unless root = User.root
      [self.group.permitted_users, root].flatten.uniq
    end
end
