module SpecRouteHelpers
  # allows tests like:
  #   route_should_be 'agama_groups#index'
  def route_should_be(route_def, options = {})
    route_hash = case route_def
      when String
        controller_name, action_name = route_def.split('#')
        #action_name = 'index' unless action_name.present?
        {controller: controller_name, action: action_name}
      else
        route_def
      end
    route_hash.merge! options
    Rails.application.routes.recognize_path(page.current_path).should include route_hash
  end

  def ember_route_should_be(route_def)
    max_wait = 4
    time = 0.0
    time_step = 0.25
    current_route = ember_route
    while time < max_wait && current_route != route_def
      time += time_step
      sleep time_step
      current_route = ember_route
    end
    ember_route(omit_should_raise: true).should == route_def
  end

  def ember_route(omit_should_raise: nil)
    # currentRouteName does not include model information: /list/123 => currentRouteName == 'list'
    # page.evaluate_script %|App.__container__.lookup('controller:application').get('currentRouteName')|
    # page.evaluate_script %|App.__container__.lookup('router:main').location.lastSetURL| # not working for direct path supplier#/settings
    route = page.evaluate_script(%{(window.MozoUser || App).__container__ && (window.location.hash || "#/").substr(1)})
    unless omit_should_raise
      def route.should(*)
        raise "Cannot call should on ember route. Use ember_route_should_be instead"
      end
    end
    route
  end
end
