require 'yaml'

module SpecSupport
  ROOT = File.join(__dir__, '../../')

  def self.blank_file
    File.join(ROOT, 'spec/support/templates/blank_file')
  end

  # for specs which write files
  def self.tmp_dir
    File.join(ROOT, 'spec/support/tmp/')
  end

  def self.db_params
    @db_params ||= begin
      conf = config['mongo']
      db_name = conf.fetch(:db)
      [db_name, conf[:host], conf[:port], conf[:user], conf[:password]]
    end
  end

  def self.db
    unless @db
      require 'mongo'
      db_name, host, port, user, password = db_params
      @db = MongoClient.new(host, port).db(db_name)
      @db.authenticate(user, password) unless user.nil? or password.nil?
    end
    @db
  end

  def self.config
    @config ||= begin
      config_file = ENV['RSPEC_CONFIG_PATH'] || File.join(ROOT, 'spec/support/config.yml')
      if File.exists?(config_file)
        YAML.load_file(config_file)
      else
        raise "There is no config file: '#{config_file}'"
      end
    end
  end

  def self.root
    File.join(__dir__, '../../')
  end
end