module ApplicationHelper

  # Given a model or collection of models, returns them with the given decorator.  If a block is passed, yields the
  # decorated objects as well
  #
  # Useful in this context:
  # <% decorate(@model_obj, ModelObjDecorator) do |model_obj| %>
  #   <%= model_obj.decorator_method %>
  # <% end %>
  def decorate(obj, decorator_class)
    decorated = decorator_class.decorate(obj, self)
    yield(decorated) if block_given?
    decorated
  end

  def timestamp(time)
    time ? time.strftime('%D %R') : ''
  end

  def nav_items
    nav = [
        nav_item('Recipes', recipes_path, 'recipes'),
        nav_item('Ingredients', ingredients_path, 'ingredients'),
        nav_item('Logs', logs_path, 'logs'),
        nav_item('Calculator', calculator_path, 'calculator'),
        nav_item('About', about_path, 'home')
    ]

    if current_user && current_user.admin?
      nav << nav_item('Admin', admin_users_path, 'admin/users')
    end

    nav
  end

  def profile_nav_items
    if current_user
      [content_tag('li', class: 'dropdown') do
         li_cnt = ''.html_safe

         li_cnt << link_to('#', class: 'dropdown-toggle', data: {toggle: 'dropdown'}, role: 'button') do
           ''.html_safe << "#{current_user.display_name}" << content_tag('span', '', class: 'caret')
         end

         li_cnt << content_tag('ul', class: 'dropdown-menu') do
           ''.html_safe << nav_item('Profile', edit_user_path) << nav_item('Logout', logout_path)
         end

         li_cnt
      end]
    else
      [nav_item('Login', login_path)]
    end
  end

  def nav_item(name, url, controller = nil)
    content_tag('li', link_to(name, url), class: active_for_controller(controller))
  end

  def active_for_controller(controller)
    if current_controller == controller
      'active'
    else
      ''
    end
  end

  def current_controller
    params[:controller]
  end
end
