run_by_appraisal = ENV["APPRAISAL_INITIALIZED"]

# simplecov somehow doesn't work well with appraisal and we don't need it to
unless run_by_appraisal
  require 'simplecov'
  SimpleCov.start do
    add_filter 'lib/calendarium-romanum/cli.rb'
  end
end

require 'aruba/rspec'

# 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.run_all_when_everything_filtered = true
  config.filter_run :focus

  # 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'
end

RSpec::Matchers.define :have_translation do |expected, locale|
  match do |actual|
    locale ||= :en
    if expected && I18n.locale == locale
      actual == expected
    else
      # with locale different from the one the spec is written for
      # just test that the string isn't left untranslated
      !(actual.nil? || actual.empty? || actual.include?('translation missing'))
    end
  end
end

require 'calendarium-romanum/cr'
require 'calendarium-romanum/cli'

I18n.enforce_available_locales = true
I18n.locale = ENV['LOCALE'] || :en

# make the gem's executable(s) easily available for aruba
gem_bin = File.expand_path('../../bin', __FILE__)
ENV['PATH'] = "#{gem_bin}:#{ENV['PATH']}"

class MarkdownDocument
  def initialize(str)
    @str = str
  end

  def each_ruby_example
    example = nil
    line = nil
    last_paragraph = ''
    paragraph_beginning = false
    @str.each_line.with_index(1) do |l, i|
      if example.nil?
        if example_beginning?(l)
          example = ''
          line = i + 1
        elsif l.strip.empty?
          paragraph_beginning = true
        elsif paragraph_beginning
          last_paragraph = l
          paragraph_beginning = false
        end
      elsif example_end?(l)
        yield example, line, last_paragraph
        example = nil
      else
        example += l
      end
    end
  end

  protected

  def example_beginning?(line)
    line =~ /^```ruby/
  end

  def example_end?(line)
    line =~ /```/
  end
end
