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

  def nutrient_row(recipe, nutrients, heading, nutrient_name)
    content_tag('tr') do
      [
          content_tag('td', heading),
          recipe.parsed_yield ? content_tag('td', nutrients.send("#{nutrient_name}_per".to_sym, recipe.parsed_yield.number)) : nil,
          content_tag('td', nutrients.send("#{nutrient_name}".to_sym))
      ].compact.join("\n".html_safe).html_safe
    end
  end

  def index_sort_header(text, field, criteria)
    uri = URI(request.original_fullpath)
    query = Rack::Utils.parse_query(uri.query)

    directions = [:asc, :desc]

    current_field = criteria.sort_column
    current_direction = criteria.sort_direction
    field_param = 'criteria[sort_column]'
    direction_param = 'criteria[sort_direction]'

    if request.get?
      is_sorted = current_field == field.to_sym

      if is_sorted && directions.include?(current_direction)
        direction = (directions.reject { |d| d == current_direction }).first
      else
        direction = directions.first
      end

      if is_sorted && direction == :asc
        link_class = 'sorted desc'
      elsif is_sorted && direction == :desc
        link_class = 'sorted asc'
      else
        link_class = 'sorted'
      end

      query[field_param.to_s] = field.to_s
      query[direction_param.to_s] = direction.to_s
      link_to text, "#{uri.path}?#{query.to_query}", class: link_class
    else
      text
    end
  end
end
