class Food < Ingredient
  include TokenizedLike

  belongs_to :user
  has_many :food_units, inverse_of: :food, dependent: :destroy

  accepts_nested_attributes_for :food_units, allow_destroy: true

  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?
      Food.none
    else
      Food.matches_tokens(:name, tokens)
    end
  end

  def cache_key
    if !self.persisted? && self.ndbn.present?
      "#{super}/#{self.ndbn}"
    else
      super
    end
  end

  def custom_units
    units = {}
    food_units.each do |fu|
      units[fu.name] = UnitConversion::parse(fu.gram_weight, "grams")
    end
    units
  end

  def nutrition_data
    self
  end

  def nutrition_unit
    UnitConversion.parse('100 grams')
  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

    copy_fields = [
        :water,
        :ash,
        :protein,
        :kcal,
        :fiber,
        :sugar,
        :carbohydrates,
        :calcium,
        :iron,
        :magnesium,
        :phosphorus,
        :potassium,
        :sodium,
        :zinc,
        :copper,
        :manganese,
        :vit_c,
        :vit_b6,
        :vit_b12,
        :vit_a,
        :vit_e,
        :vit_d,
        :vit_k,
        :cholesterol,
        [:lipids, :lipid],
        [:density, :density_best_guess]
    ]

    copy_fields.each do |f|
      to, from = f.is_a?(Array) ? f : [f, f]
      self.send("#{to}=".to_sym, food.send(from.to_sym))
    end
  end

end
