
ENV["RAILS_ENV"] = "test"

require 'simplecov'
require 'support/utilities'
require 'support/profile'
require 'support/maxmind'
require 'support/lesson_session'
require 'active_record'
#require 'jam_db'
require 'spec_db'
require 'uses_temp_files'
require 'resque_spec'
require 'resque_failed_job_mailer'
require 'stripe_mock'


# to prevent embedded resque code from forking
ENV['FORK_PER_JOB'] = 'false'
IS_BUILD_SERVER = !ENV['BUILD_SERVER'].nil?

# recreate test database and migrate it
#SpecDb::recreate_database
JamRuby::TestSupport.recreate_database if ENV['SKIP_DB_PREP'].nil?

# initialize ActiveRecord's db connection
ActiveRecord::Base.establish_connection(YAML::load(File.open('config/database.yml'))["test"])
ActiveRecord::Base.raise_in_transactional_callbacks = true

# so jam_ruby models that use APP_CONFIG in metadata will load. this is later stubbed pre test run
APP_CONFIG = app_config

require 'jam_ruby'
require 'factory_girl'
require 'rubygems'
require 'spork'
require 'database_cleaner'
require 'factories'

require 'timecop'
require 'resque_spec/scheduler'

# uncomment this to see active record logs
# ActiveRecord::Base.logger = Logger.new(STDOUT) if defined?(ActiveRecord::Base)

include JamRuby

# manually register observers
ActiveRecord::Base.add_observer InvitedUserObserver.instance
ActiveRecord::Base.add_observer UserObserver.instance
ActiveRecord::Base.add_observer FeedbackObserver.instance
ActiveRecord::Base.add_observer RecordedTrackObserver.instance
ActiveRecord::Base.add_observer RecordedBackingTrackObserver.instance
ActiveRecord::Base.add_observer QuickMixObserver.instance

#RecordedTrack.observers.disable :all # only a few tests want this observer active

# put ActionMailer into test mode
ActionMailer::Base.delivery_method = :test

# set up carrierwave to use file (instead of say, fog) for testing
CarrierWave.configure do |config|
    config.storage = :file
    config.enable_processing = false
end

Stripe.api_key = "sk_test_OkjoIF7FmdjunyNsdVqJD02D"


Recurly::API.net_http = {
    ssl_version: :TLSv1_2,
    #...
}

#uncomment the following line to use spork with the debugger
#require 'spork/ext/ruby-debug'

#Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However,
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  # This file is copied to spec/ when you run 'rails generate rspec:install'
  #ENV["RAILS_ENV"] ||= 'test'
  #require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/autorun'
  #require 'rspec/rails'
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# Require this file using `require "spec_helper"` to ensure that it is only
# loaded once.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
  RSpec.configure do |config|

    config.color_enabled = true
    config.treat_symbols_as_metadata_keys_with_true_values = true
    config.run_all_when_everything_filtered = true
    config.filter_run :focus

    #config.formatter = :documentation


    # you can mark a test as slow so that developers won't commonly hit it, but build server will http://blog.davidchelimsky.net/2010/06/14/filtering-examples-in-rspec-2/
    config.filter_run_excluding slow: true unless run_tests? :slow
    config.filter_run_excluding aws: true unless run_tests? :aws
    config.filter_run_excluding intermittent: true if IS_BUILD_SERVER

    config.before(:suite) do
      DatabaseCleaner.strategy = :transaction
      DatabaseCleaner.clean_with(:deletion, {pre_count: true, reset_ids:false, :except => %w[gift_card_types lesson_package_types instruments languages subjects genres icecast_server_groups jamcompany jamisp geoipblocks geoipisp geoiplocations cities regions countries generic_state spatial_ref_sys] })
    end

    config.around(:each) do |example|
      # set  no_transaction: true as metadata on your test to use deletion strategy instead
      if example.metadata[:no_transaction]
        DatabaseCleaner.strategy = :deletion, {pre_count: true, reset_ids:false, :except => %w[gift_card_types lesson_package_types instruments languages subjects genres icecast_server_groups jamcompany jamisp geoipblocks geoipisp geoiplocations cities regions countries generic_state spatial_ref_sys] }
      else
        DatabaseCleaner.strategy = :transaction
      end

      DatabaseCleaner.start
      example.run
    end

    config.before(:each) do
      stub_const("APP_CONFIG", app_config)
    end

    config.after(:each) do
      Timecop.return
      DatabaseCleaner.clean
    end

    config.after(:suite) do
      wipe_s3_test_bucket
    end

    # 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

    # Run specs in random order to surface order dependencies. If you find an
    # order dependency and want to debug it, you can fix the order by providing
    # the seed, which is printed after each run.
    #     --seed 1234
    config.order = 'random'

    REDIS_PID = "#{Rails.root}/tmp/pids/redis-test.pid"
    REDIS_CACHE_PATH = "#{Rails.root}/tmp/cache/"
    config.before(:suite) do
      redis_options = {
        "--daemonize"     => 'yes',
        "--pidfile"       => REDIS_PID,
        "--port"          => 9736,
        "--timeout"       => 300,
        "--save 900"      => 1,
        "--save 300"      => 1,
        "--save 60"       => 10000,
        "--dbfilename"    => "dump.rdb",
        "--dir"           => REDIS_CACHE_PATH,
        "--loglevel"      => "debug",
        "--logfile"       => "stdout",
        "--databases"     => 16
      }.map { |k, v| "#{k} #{v}" }.join(" ")
      `redis-server #{redis_options}`
    end
    config.after(:suite) do
      %x{
      cat #{REDIS_PID} | xargs kill -QUIT
      rm -f #{REDIS_CACHE_PATH}dump.rdb
      }
    end
  end
#end

#Spork.each_run do
  # This code will be run each time you run your specs.
#end
