# Applicaton helper methods
module ApplicationHelper
  def menu_top(pages)
    ret = ''
    pp = PublishedPage.finder(params[:id]).first
    friendly_id = pp && pp.type_of == 3 ? pp.article_friendly : params[:id]
    pages.each do |page|
      if !friendly_id.blank?
        ret +=
          "<li#{friendly_id.include?(page.friendly_id) ? " class='active'" : ''}><a href='/site/#{page.friendly_id}'>#{page.name}</a></li>"
      else
        ret += '<li><a href="/site/' + page.friendly_id + '">' + page.name + '</a></li>'
      end
    end
    ret
  end

  def render_list_for_categories(categories)
    ret = ''
    categories.each do |node|
      ret += '<li>'
      size = node.active_childrens.size
      if size.zero?
        ret += link_to(node.name, category_path(node))
      else
        ret += link_to(raw("#{node.name} <i class=\"fa fa-angle-right pull-right\"></i>"), category_path(node), class: 'dropdown-toggle')
        columns = (size.to_f / 12).ceil
        position = 0
        if columns > 1
          ret += "<ul class=\"dropdown-menu multi-column columns-#{columns}\">"
          ret += '<div class="row">'
        end
        node.active_childrens.each do |n|
          if position.zero? && columns > 1
            ret += '<div class="col-md-' + (12 / columns).to_s + '"><ul class="multi-column-dropdown">'
          elsif position.zero?
            ret += '<ul class="dropdown-menu">'
          end
          position += 1
          ret += '<li>'
          ret += link_to(n.name, category_path(n))
          ret += '</li>'
          next unless position == 12
          ret += '</ul>'
          ret += '</div>' if columns > 1
          position = 0
        end
        if position > 0 && position < 12
          ret += '</ul>'
          ret += '</div>' if columns > 1
        end
        if columns > 1
          ret += '</div>'
          ret += '</ul>'
        end
      end
      ret += '</li>'
    end
    ret
  end

  def raise_404(object)
    raise ActionController::RoutingError, 'Not Found' if object.blank?
  end

  # generate errors html
  def errors_to_html(errors)
    ret = '<div class="row"><div class="col-lg-12 col-md-12 panel-danger">'\
      '<div class="content-box-header panel-heading"><div class="panel-title">'
    ret += I18n.t('activerecord.errors.messages.record_invalid',
                  errors: errors.count)
    ret += '</div></div><div class="content-box-large box-with-header"'\
      ' style="background:#f9dddd"><ul>'
    errors.full_messages.each do |msg|
      ret += "<li>#{msg}</li>"
    end
    ret += '</ul></div></div></div>'
    ret
  end
end
