module ApplicationHelper
  def title(*args)
    res = content_tag :h1, class: 'page-title' do
      if args.first.is_a?(Symbol) && (args[1].respond_to?(:model_name) || args[1].class.respond_to?(:model_name))
        model = args[1].respond_to?(:model_name) ? args[1] : args[1].class
        if args.first == :index
          t('action.index.label', models: model.model_name.human_plural)
        else
          t("action.#{args.first}.label", model: model.model_name.human)
        end
      else
        args.first
      end
    end
    content_for :page_title, res
    res
  end

  # overwrite i18n l, to handle nil values
  def l(*args)
    return '' unless args.first
    super(*args)
  end

  def user_root_path
    case Rails.env
    when 'development' then 'http://localhost:4200/'
    else '/user/index.html'
    end
  end

  def user_dynamic_data_host
    case Rails.env
    when 'test' then "$data_host = data_host = 'http://#{request.host}:#{request.port}';".html_safe
    when 'development' then "$data_host = data_host = 'http://localhost:3000';".html_safe
    else ''
    end
  end

  def user_dynamic_root_url
    case Rails.env
    when 'test' then "Qstorage.setItem('root_url', 'http://#{request.host}:#{request.port}/user/index.html');".html_safe
    when 'development' then "Qstorage.setItem('root_url', 'http://localhost:3000/user/index.html');".html_safe
    else ''
    end
  end

  def user_dynamic_obtain_token_url
    case Rails.env
    when 'test' then "$obtain_token_url = 'http://#{request.host}:#{request.port}/user/obtain_token.html';".html_safe
    when 'development' then "$obtain_token_url = 'http://localhost:3000/user/obtain_token.html';".html_safe
    else ''
    end
  end

  def app_version
    File.read(Rails.root.join('config/version')).strip
  end

  def are_you_sure?(record = nil)
    t('helpers.links.are_you_sure')
  end

  def active_list
    active_list_object
  end

  def application_title
    'mozo.bar'
  end

  def site_page_title
    application_title
  end

  def waiter_page_title
    application_title
  end

  # Helper for displaying HTML currency values
  def currency(amount, opts={})
    amount ||= 0.0
    amount = amount.to_f
    #prefix = case company.currency
    #         when 'GBP' then '&pound;&nbsp;'
    #         when 'USD' then '$&nbsp;'
    #         else '&euro;&nbsp;'
    #         end
    prefix = '&euro;&nbsp;'
    return (prefix + ("%.2f" % amount)).html_safe

    # Rails native is ambiguous since is uses translation hashes
    options = {:unit => '&euro;'}.merge(opts)
    number_to_currency(amount, options)
  end
  def list_open?
    active_list_id.present?
  end

  def active_list_id
    current_user.try(:active_list_id)
  end

  #def week_days
    #@week_days ||= %w[sunday monday tuesday wednesday thursday friday saturday].freeze # Do not allow changing this value
  #end

  def current_supplier
    #@current_supplier ||= ActiveDecorator::Decorator.instance.decorate(super)
    @current_supplier ||= super
    ActiveDecorator::Decorator.instance.decorate @current_supplier
    @current_supplier
  end

  def no_content_given(model)
    content_tag(:p, t('helpers.list.no_records'), data: {t: 'helpers.list.no_records'})
  end

  def slider_image
    image_tag('spinner.gif')
  end

  def spinner
    image_tag('spinner.gif')
  end

  def show_boolean(bool)
    t("general.boolean.boolean_#{bool.present? ? 'yes' : 'no'}")
  end

  def facebook_link
    link_to 'Facebook', 'https://www.facebook.com/mozo.bar', target: :_blank
  end
  def twitter_link
    link_to 'Twitter', 'https://www.twitter.com/mozo.bar', target: :_blank
  end

  # Add a script call to be executed when the dom is loaded.
  # When called without a script it will return the total added script content
  #  - onload_javascript 'var a=1'
  #  - onload_javascript 'var b=3'
  #  = onload_javascript #=> var a=1;var b=3
  def onload_javascript(script = nil)
    if block_given?
      script = script.to_s
      value = nil
      buffer = with_output_buffer {  value = yield }
      script += (buffer.presence || value).to_s
    end
    script = script.call if script.respond_to?(:call)
    script.sub!(/^<script[^>]+>/,'') if script
    script.sub!(/<\/script>$/, '') if script
    script.present? ? (@onload_javascripts ||= []) << script : (@onload_javascripts || []).join(';').html_safe
  end

  def mustache_template(template)
    render(template, handlers: [:mustache])
  end

  def top_bar(options = {}, &block)
    title = options[:title]
    title = title.present? ? content_tag(:h3, t("user.#{title}"), class: 'title', data: {t: title}) : ''
    content_tag :div, class: 'top-button-bar' do
      content_tag :div, class: 'button-bar-inner' do
        content_tag :div, class: 'button-bar-content' do
          (title + capture(&block)).html_safe
        end
      end
    end
  end

  def find_page(name)
    Page.find_by_name_and_locale(name, I18n.locale)
  end

  def locale_root_path
    I18n.locale == I18n.default_locale ? '/' : "/#{I18n.locale}"
  end

  def link_to_function(title, function, options={})
    options[:onclick] = function
    link_to title, 'javascript:void(0)', options
  end

  # Return active or nil based on the given route spec
  #   %li{ class: active_class('users') # true if controller is users, false otherwise
  #   %li{ class: active_class('pages#about') # true if controller is pages and action is about
  def active_class(*route_specs)
    options = route_specs.extract_options!
    active_class = options.delete(:active_class) || 'active'
    return_class = Array.wrap(options.delete(:default_class))
    if route_specs.map{|rs| current_route_spec?(rs) }.any?
      if params.slice(*options.keys) == options.stringify_keys
        return_class << active_class
      end
    end
    return_class
  end

  # Check if the current route matches the route given as argument.
  # The syntax is meant to be a bit similar to specifying routes in
  # `config/routes.rb`.
  #   current_route_spec?('products') #=> true if controller name is products, false otherwise
  #   current_route_spec?('products#show') #=> true if controller_name is products AND action_name is show
  #   current_route_spec?('#show') #=> true if action_name is show, false otherwise
  #NOTE: this helper is tested through the active_class helper
  def current_route_spec?(route_spec)
    controller, action = route_spec.split('#')
    if controller and controller_path == controller
      if action
        if action_name == action
          true
        end
      else
        # no action means all actions of controller
        true
      end
    else
      if action_name == action
        true
      end
    end
  end

  # used for rendering page trees
  def tree_ul(acts_as_tree_set, options = {}, &block)
    # If only one option is given, a select is assumed
    options = {:select => options} unless options.is_a?(Hash)
    # Ensure a select option
    options[:select] ||= lambda{|p| true}
    options[:select] = options[:select].to_proc if options[:select].is_a?(Symbol)
    block ||= lambda{|item| item.name }
    acts_as_tree_set.reject!{|m| not options[:select].call(m)}
    ret = ''
    if acts_as_tree_set.size > 0
      if list_id = options.delete(:list_id).presence
        ret = %|<ul id="#{list_id}">|
      else
        ret = "<ul>"
      end
      acts_as_tree_set.collect do |item|
        #next if item.parent_id && init
        ret += '<li>'
        ret += capture(item, &block)
        #tmp = tree_ul(item.children, checker, &block) if item.children.size > 0
        #return "#{tmp} is no valid result\n\n" unless tmp.is_a?(String)
        #ret += tmp
        ret += tree_ul(item.children, options, &block) if item.children.size > 0
        ret += '</li>'
      end
      ret += '</ul>'
    end
    ret.html_safe
  end
end
