class NutritionData

  NUTRIENTS = [
      :protein,
      :lipids,
      :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
  ]

  attr_reader :errors
  attr_reader *NUTRIENTS

  def initialize(recipe_ingredients)
    @errors = []

    NUTRIENTS.each do |n|
      self.instance_variable_set("@#{n}".to_sym, 0.0)
    end

    valid_ingredients = []

    recipe_ingredients.each do |i|
      if i.ingredient_id.nil?
        @errors << "#{i.name} has no nutrition data"
      elsif !i.can_convert_to_grams?
        @errors << "#{i.name} can't be converted to grams"
      else
        valid_ingredients << i
      end
    end

    valid_ingredients.each do |i|
      grams = i.to_grams

      NUTRIENTS.each do |k|
        value = i.ingredient.send(k)
        if value.present?
          value = value.to_f
          running_total = self.instance_variable_get("@#{k}".to_sym)
          delta = (grams / 100.0) * value
          self.instance_variable_set("@#{k}".to_sym, running_total + delta)
        else
          @errors << "#{i.name} missing #{k} data"
        end
      end
    end

    NUTRIENTS.each do |k|
      v = self.instance_variable_get("@#{k}".to_sym)
      self.instance_variable_set("@#{k}".to_sym, v.round(2))
    end

  end

end