# This file is copied to spec/ when you run 'rails generate rspec:install'
#require 'simplecov'
#SimpleCov.start 'rails'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../config/environment", File.dirname(__FILE__))
require 'rspec/rails'
require 'rspec/matchers'
require 'capybara/rspec'
require 'turnip/capybara'
require 'in_memory_q_counter'
require 'capybara-screenshot/rspec'
require 'webmock/rspec'
#require 'capybara/poltergeist'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
#Dir[Rails.root.join("spec/factories/**/*.rb")].each {|f| require f }
Dir.glob("spec/acceptance_steps/**/*steps.rb") { |f| load f, true }

I18n.locale =I18n.default_locale
Devise.stretches = 1
#Capybara.javascript_driver = :webkit
#Capybara.javascript_driver = :poltergeist
Capybara.javascript_driver = :selenium
Capybara.default_max_wait_time = 5 # ember needs more time than the default of 2
Capybara.server_port = 62625
Capybara::Screenshot.webkit_options = { width: 1024, height: 768 }
WebMock.disable_net_connect!(allow_localhost: true)

#Capybara.javascript_driver = :selenium
module TurnipHacks
  def run_step(*)
    # delay for a nice follow in selenium
    #sleep 0.6
    super
  end
end

module FactoryAttributesFor
  def attributes_for(obj, options={})
    super(obj, options).merge(build(obj).attributes.select{|k,v| k =~ /_id$/}).symbolize_keys
  end
end

module RequestSpecHelpers
  module MethodsForHash
    def method_missing(m, *args)
      r = self[m.to_s.dasherize]
      if r.is_a?(Hash)
        r.extend MethodsForHash
      end
      r
    end
  end
  def api_response
    result = JSON.parse(response.body)
    result.extend MethodsForHash
    #result.extend Hashie::Extensions::DeepFind
    result
  end
end

module SpecSelectorHelpers
  def top_navigation
    '.navbar-fixed-top'
  end

  # Uses the click_on method for capybara
  def click_on_translation(key)
    text = I18n.t(key)
    text.should_not =~ /missing/
    click_on text
  end

  # same as save_and_open_page but with styling
  def show_page
    save_page Rails.root.join( 'public', 'capybara.html' )
    %x(launchy http://localhost:3000/capybara.html)
  end

end

class Ability
  include CanCan::Ability
  def initialize(record)
    can :manage, :All
  end
end
class TestCounter < InMemoryQCounter
  #def incr(*args)
    #result = super
    #puts "Counter incr called with #{args.inspect} giving result #{result}"
    #result
  #end
end

# No external images in test suite... slow....
User.send(:define_method, :avatar, ->{})


if defined?(Couchbase)
  class Couchbase::View
    alias :old_initialize :initialize
    def initialize(bucket, endpoint, params = {})
      old_initialize(bucket, endpoint, params.merge(stale: false))
    end
  end
end

RSpec.configure do |config|
  # == Mock Framework
  #
  # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
  #
  # config.mock_with :mocha
  # config.mock_with :flexmock
  # config.mock_with :rr
  #config.mock_with :rspec
  config.include FactoryGirl::Syntax::Methods
  config.include FactoryAttributesFor
  config.include Devise::TestHelpers, type: :controller
  config.include SpecControllerHelpers, type: :controller
  config.include EndWithMatcher
  config.include Matchers
  config.include TurnipHacks, turnip: true
  config.include ActiveSupport::Testing::TimeHelpers
  config.include Features::BasicHelpers, type: :feature
  config.include SpecRouteHelpers, type: :feature
  config.include SpecEmberHelpers, type: :feature
  config.include SerializersTestHelpers, type: :serializer
  config.include Warden::Test::Helpers, type: :request
  config.include RequestSpecHelpers, type: :request
  #config.use_transactional_fixtures = true
  config.infer_base_class_for_anonymous_controllers = true
  config.filter_run_excluding broken: true
  config.render_views = true
  config.expect_with(:rspec) { |c| c.syntax = [:expect, :should] }

  OmniAuth.config.test_mode = true
  OmniAuth.config.add_mock :facebook, {
    info: {
      nickname: 'Joey',
      name: "Facebook Joe",
      first_name: "Facebook Joe"
    },
    credentials: {
      'token' => 'fbAuthToken234',
      'expires_at' => 1.week.from_now.to_i,
      'expires' => true
    },
    uid: '123456790'
  }

  OmniAuth.config.add_mock :instagram, {
    info: {
      nickname: 'Iggy',
      name: "Instagram Jane",
      first_name: "Insta"
    },
    credentials: {
      'token' => 'igAuthToken234',
      'expires_at' => 1.week.from_now.to_i,
      'expires' => true
    },
    uid: '123498765'
  }

  # Use color in STDOUT
  config.color = true
  config.fail_fast = false

  # Use color not only in STDOUT but also in pagers and files
  config.tty = true

  # Use the specified formatter
  #config.formatter = :documentation # :progress, :html, :textmate

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  #config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  #config.use_transactional_fixtures = true
  config.before :suite do
    Qwaiter::Couchbase.load_design_docs!
    Qwaiter::Counter.connection = TestCounter.new
  end

  config.before :each do
    CouchPotato.couchrest_database.recreate!
    Qwaiter::Counter.connection.flush
  end

  config.before :each, type: :feature do
    #Supplier.any_instance.stub send_confirmation_instructions: true
    Capybara.session_name = :default
  end

  config.around :each, type: :request do |example|
    Warden.test_mode!
    example.run
    Warden.test_reset!
  end


  config.after :suite do
=begin
    rspec_outfile = Rails.root.join('coverage/rspec_results.html')
    result = File.read rspec_outfile
    replacement = %|<body><div><a href="index.html" style="padding:4px 8px;background-color:#393;color:white;font-weight:bold;border:2px #050 outset">Coverage</a></div>|
    result.gsub! /<body>/, replacement
    File.open(rspec_outfile, 'w'){|f| f.puts result}
    `open #{rspec_outfile}`
=end
  end

  # If true, the base class of anonymous controllers will be inferred
  # automatically. This will be the default behavior in future versions of
  # rspec-rails.
  #config.infer_base_class_for_anonymous_controllers = true
end
