module ApplicationHelper
  
  def all_params_match?(hash1, hash2)
    
    hash2.each do |key, value|
      
      if hash1[key].is_a? Hash
        if all_params_match?(hash1[key], value)
          hash1.delete(key)
        end
      else
        hash1.delete(key) if hash1[key].to_s == value.to_s
      end      
    end
    hash1.empty?
  end
  
  # Includes the global script and additional stylesheets based on the controller and action.
  #
  # For example when the rendered action is Profile::RecipesController#show, it will include:
  # - defaults.js
  # - profile.js
  # - profile/recipes.js
  # - profile/recipes/show.js
  #
  # It also includes all content for the :scripts symbol.
  def include_default_scripts
    includes = []

    includes << javascript_include_tag(:application) if assets_exists? "application.js"
    includes << content_for(:external_scripts)

    default_asset_paths.each do |path|
      if assets_exists? "#{path}.js"
        includes << javascript_include_tag(path)
      end
    end
    
    includes << content_for(:scripts)
    includes.join("\n").html_safe
  end

  def default_asset_paths

    path_fragments = params[:controller].split("/")
    root = path_fragments.shift
    assets_paths = path_fragments.inject([root]) { |paths, path_fragment| paths + ["#{paths.last}/#{path_fragment}"] }
    assets_paths += ["#{params[:controller]}/#{params[:action]}"]

    assets_paths
  end

  def assets_exists? asset_path
    Tf::Application.assets.find_asset asset_path
  end

  # wicker pdf throw undefined path to paperclip images
  def wicked_pdf_image_tag_for_public(img, options={})
    if img[0] == "/"
      new_image = img.slice(1..-1)
      image_tag "file://#{Rails.root.join('public', new_image)}", options
    else
      image_tag "file://#{Rails.root.join('public', 'images', img)}", options
    end
  end  

  # get full image url
  def image_url(file)
    request.protocol + request.host_with_port + path_to_image(file)
  end
end
