class MealPortion < ApplicationRecord
  include PortionsHelper
  belongs_to :meal #, optional: true
  belongs_to :portion

  validates_uniqueness_of :meal_id, :scope => :portion_id
  has_many :substitutes, as: :equalable
  accepts_nested_attributes_for :substitutes, :allow_destroy => true

  attr_accessor :substitutes_selector
  default_scope { order(number: :asc) }

  def shortcut
    if portion
      [humanize_portion(quantity), unidad, portion.name].join(" ")
    else
      return ""
    end
  end

  def unit
    self.portion.unit
  end

  def unidad
    case self.unit
    when "portion"
      return "#{quantity.to_f > 1.0 ? 'porciones' : 'porción' } de"
    when "tz"
      return "#{quantity.to_f > 1.0 ? 'tazas' : 'taza' } de"
    when "pz"
      return "#{quantity.to_f > 1.0 ? 'piezas' : 'pz' } de"
    when "gr"
      return "g. de"
    when "cda"
      return "#{quantity.to_f > 1.0 ? 'cucharadas' : 'cucharada' } de"
    else
      return self.unit
    end
  end

  def facts
    "<span>Cal: #{calories}</span><span>Prot: #{proteins}</span><span>Carb: #{carbs}</span><span>Grasa #{fats}</span>"
  end

  def calories
    return get_fact(portion.calories) if portion
    return 0
  end

  def proteins
    return get_fact(portion.proteins) if portion
    return 0
  end

  def carbs
    return get_fact(portion.carbs.to_f) if portion
    return 0
  end

  def fiber
    return get_fact(portion.fiber) if portion
    return 0
  end

  def fats
    return get_fact(portion.fats) if portion
    return 0
  end

  private

  def get_fact(fact)
    return ((fact.to_f * quantity.to_f) / portion.quantity.to_f).round(2)
  end

end