class Import < ActiveRecord::Base
  belongs_to :user

  validates :date, :presence => true
  validates :item, :presence => true, :length => { :maximum => 256 }
  validates :cents, :presence => true, :numericality => true
#  validates :currency, :presence => true
  validates :account, :presence => true
  validates :category, :presence => true
  validate :amount_is_properly_formatted
  validate :account_belongs_to_user
  validate :category_exist

  composed_of :amount,
      :class_name => "Money",
      :mapping => [%w(cents cents), %w(currency currency_as_string)],
      :constructor => Proc.new { |cents, currency|
          Money.new(cents || 0, currency || Money.default_currency)
        },
      :converter => Proc.new { |value|
          value.respond_to?(:to_money) ?
              value.to_money :
              raise(ArgumentError, "Can't convert #{value.class} to Money")
        }

  def amount_is_properly_formatted
    begin
      errors.add(:currency, "is unknown") if Money::Currency.find(currency).nil?
    rescue
      errors.add(:amount, "is not properly formatted")
      return false
    end
  end

  def account_belongs_to_user
    errors.add(:account, "does not belongs to user") if User.find(user_id).accounts.find_by_name(account).nil?
  end
 
  def category_exist
    errors.add(:category, "does not exist") if Category.find_by_name(category).nil?
  end

end
