class Ingredient < ActiveRecord::Base
  include TokenizedLike

  belongs_to :user

  validates :name, presence: true
  validates :density, density: true, allow_blank: true

  scope :has_density, -> { where.not(density: nil) }

  def self.search(query)
    tokens = query.to_s.split(' ')

    if tokens.empty?
      Ingredient.none
    else
      Ingredient.matches_tokens(:name, tokens)
    end
  end

  def ndbn=(value)
    @usda_food = nil
    super
  end

  def usda_food
    if self.ndbn.present?
      @usda_food ||= UsdaFood.find_by_ndbn(self.ndbn)
    else
      nil
    end
  end

  def usda_food_name
    if usda_food
      usda_food.long_description
    end
  end

  def set_usda_food(food)
    return unless food

    self.ndbn = food.ndbn
    self.water = food.water
    self.protein = food.protein
    self.lipids = food.lipid
    self.carbohydrates = food.carbohydrates
    self.ash = food.ash
    self.kcal = food.kcal
    self.fiber = food.fiber
    self.sugar = food.sugar
    self.density = food.density_best_guess
  end

end
