class Conversion
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :input_quantity, :input_units, :scale, :output_units, :ingredient_id
  attr_reader :output_quantity

  validates :input_quantity, presence: true
  validate :check_conversion, :if => Proc.new { |object| object.errors.empty? }

  def initialize(attrs = nil)
    if attrs
      attrs.each do |k, v|
        send("#{k}=", v)
      end
    end

    @output_quantity = nil
  end

  def check_conversion
    begin
      ingredient = ingredient_id.blank? ? nil : Food.find(ingredient_id)
      scale = self.scale.blank? ? '1' : self.scale
      density = ingredient.nil? ? nil : ingredient.density
      @output_quantity = UnitConversion.convert(input_quantity, scale, input_units, output_units, density)
    rescue UnitConversion::UnparseableUnitError => err
      errors[:base] << "Invalid Data: #{err.message}"
    end
  end

  def persisted?
    false
  end
end