require 'digest/sha1'

# this model expects a certain database layout and its based on the name/login pattern.
class User < ActiveRecord::Base
  attr_protected :super_user
  has_many :own_groups, :class_name => "Group", :foreign_key => "owner_id", :dependent => :destroy
  #has_many :belonging_groups, :through => :group_members, :source => :group, :order => :name

  def self.authenticate(login, pass)
    return nil if GFDNAVI_DISABLE_USER
    find(:first,
         :conditions => ["login = ? AND password = ?", login, sha1(pass)])
  end

  def self.super_user?(user)
    return nil if GFDNAVI_DISABLE_USER
    user.super_user?
  end

  def super_user?
    super_user == true
  end

  def change_password(pass, pass_confirm)
    unless pass == pass_confirm
      return false
    end
    self.password = User.sha1(pass)
    self.save
  end

  def belonging_groups
    Group.find_by_bit_flag(groups)
  end

  protected

  def self.sha1(pass)
    Digest::SHA1.hexdigest("#{GFDNAVI_PASSPHRASE}--#{pass}--")
  end

  before_create :crypt_password

  def crypt_password
    write_attribute("password", self.class.sha1(password))
  end

=begin
  def after_create
    group = self.own_groups.create(:name => self.login)
    group.members = [self]
  end
=end

  validates_length_of :login, :within => 3..10
  validates_length_of :password, :within => 5..40
  validates_presence_of :login, :password, :full_name, :email_address, :affiliation
  validates_presence_of :password_confirmation, :on => :create
  validates_confirmation_of :password, :on => :create
  validates_uniqueness_of :login
  validates_format_of :email_address, :with => /^(\w|-)+@(\w|-)+\.(\w|-)+/, :message => "email address is invalid"

end
