module RecipesHelper
  def recipe_time(recipe)
    output = ''.html_safe

    if recipe.total_time.present?
      output << "#{humanize_seconds(recipe.total_time.to_i.minutes)}"
      if recipe.active_time.present?
        output << " (#{humanize_seconds(recipe.active_time.to_i.minutes)} active)"
      end
    elsif recipe.active_time.present?
      output << humanize_seconds(recipe.active_time.to_i.minutes)
    end

    output
  end

  def humanize_seconds(secs)
    [[60, :s], [60, :m], [24, :h], [1000, :d]].map{ |count, name|
      if secs > 0
        secs, n = secs.divmod(count)
        n == 0 ? nil : "#{n.to_i} #{name}"
      end
    }.compact.reverse.join(' ')
  end
end
